When replace word file content and save the word file, for loop only loops once

Viewed 23

My goal is to replace some specific content in word file, and then save the file to the old directory. I would like to do replace the same word file and generate multiple files. I used for loop and it failed to generate 3 files instead of only 1 file. I still can't see where the problem is. Can somebody help me ? Codes are like this:

from docx import Document
import os


def main():
    path = r'C:\Users\Sharon.X.Fang\Desktop'
    EXPERT_NAME = ['Yang','Xie','Wang']
    template_file_path = path+os.sep+'to Mr.Xie-invitation.docx'
    i = 0
    for name in EXPERT_NAME:
        for i in range(3):
            output_file_path = path+os.sep+str(i)+'to Mr.'+name+'-invitation.docx'
    i = i + 1

    variables = {
        "${EXPERT_NAME}": "Mr.Xie",
        "${Fee}": "1,000",
        "${Q_1}": "What is your hobby?",
        "${Q_2}": "How are you?",
                }
    
    template_document = Document(template_file_path)

    for variable_key, variable_value in variables.items():
        for paragraph in template_document.paragraphs:
            replace_text_in_paragraph(paragraph, variable_key, variable_value)

    template_document.save(output_file_path)
    

def replace_text_in_paragraph(paragraph, key, value):
    if key in paragraph.text:
       paragraph.text = paragraph.text.replace(key, value)
   
            
if __name__ == '__main__':
    main()
1 Answers

I think the main problem was you had the document creation outside your loop:

def main():
    path = r'C:\Users\Sharon.X.Fang\Desktop'
    EXPERT_NAMES = ['Yang','Xie','Wang']
    template_file_path = path+os.sep+'to Mr.Xie-invitation.docx'

    for i, name in enumerate(EXPERT_NAMES):
        output_file_path = (
            path+os.sep+str(i)+'to Mr.'+name+'-invitation.docx'
        )

        variables = {
            "${EXPERT_NAME}": name,
            "${Fee}": "1,000",
            "${Q_1}": "What is your hobby?",
            "${Q_2}": "How are you?",
        }
    
        template_document = Document(template_file_path)
        replace_text_in_document(template_document, variables)
        template_document.save(output_file_path)


def replace_text_in_document(document, variables):    
    for variable_key, variable_value in variables.items():
        for paragraph in document.paragraphs:
            replace_text_in_paragraph(
                paragraph, variable_key, variable_value
            )


def replace_text_in_paragraph(paragraph, key, value):
    if key in paragraph.text:
       paragraph.text = paragraph.text.replace(key, value)
   
            
if __name__ == '__main__':
    main()
Related