lundi 13 juin 2016

replace text from docx using Python

I have a little side project I'm doing at work to help me with the "manual" labor of creating welcome documents for employees.

What I'm trying to do is: 1) Extract cell contents from a CSV file (username, first name, password) 2) Take cell contents and replace the strings [FirstName], [Username] and [Password] in the DOCX file.

This is the code:

""" Dependencies """
import csv
import numpy as np
import re
import shutil
import docx
#import fileinput

""" Open CSV and add usernames to list """
with open('UploadUsers.csv', 'rU') as csvfile:
    readCSV = np.loadtxt(csvfile, delimiter=',', skiprows=1, dtype = 'str')
    first_names = []
    usernames = []
    passwords = []

for row in readCSV:
    username = row[1]
    first_name = row[2]
    password = row[5]

    usernames.append(username)
    first_names.append(first_name)
    passwords.append(password)

for username in usernames:

    doc = "Free_Tracking_Manager_US.docx"
    doc_copy = "Free_Tracking_Manager_US.docx."+username+".docx"

    """ Make file copies """
    shutil.copy(doc, doc_copy)

    """ Make changes to first name, username and password """

    document = docx.Document(doc_copy)

    for paragraph in document.paragraphs:
        if '[FirstName]' in paragraph.text:
            print(first_name)
        if '[Username]'  in paragraph.text:
            print(username)
        if '[Password]'  in paragraph.text:
            print(password)

    """ Save document """
    document.save(doc_copy)

The script runs without errors, it makes copies of the documents but doesn't replace the strings. Not sure where the issue is...

Aucun commentaire:

Enregistrer un commentaire