Search code examples
pythonfor-loopzipdocxf-string

python append two zipped lists into docx file


john = [...]
jake = [...]       

for a,b in zip(john, jake):
    document = Document()
    document.add_paragraph(f"{a}---------------{b} \n")
    document.save("docxpy.docx")

I have two lists and want to append their values as "a----------------b" into "docxpy.docx" file. But every single time it appends only one of them. I am new to python please font make fun of me


Solution

  • Try this:

    john = [...]
    jake = [...]       
    
    document = Document() # this needs to be before the for loop
    
    for a,b in zip(john, jake):
        document.add_paragraph(f"{a}---------------{b} \n")
    
    document.save("docxpy.docx") # this should come after the for loop
    

    The problem is you initialized document inside the loop, which means every iteration it's reinitializing document with an empty Document() object. As a result, at the last iteration of your loop, you end up with a document that only contains the very last pair of a,b, which is why you see only one line in your output document. Initializing the document variable before the for loop should do the trick.

    In addition, you should put the save method call after the loop. This isn't strictly necessary (you'll notice you get the same result either way), but it saves time/resources since you need only write the file to disk once at the very end once all the paragraphs have been added.