如何阻止python循环堆叠信息

时间:2018-05-21 12:09:13

标签: python for-loop while-loop python-docx

我打算在python中自动化一些使用while循环创建几个.docx文件的东西。每个文件都有自己唯一的名称,并在其中包含一些信息。我的问题是,当循环时,我在文档中获得的信息是堆叠的。

我相信有一个简单的解决方案,我似乎无法找到它。

以下是代码块:

i=1
while i < 10:
    os.chdir("C:\\Users\\user\\Desktop\\" +FolderName)
    doc.save(str(doc_number[i])+str(essay_type[i])+' '+str(titles[i])+' '+str(writer[i])+'.docx');
    doc.add_paragraph('Title/Keyword:'+str(titles[i]));
    doc.add_paragraph('Reasech Link:'+str(link[i]));
    doc.add_paragraph('Target Site:'+str(keyword[i]));
    doc.save(str(doc_number[i])+str(essay_type[i])+' '+str(titles[i])+' '+str(writer[i])+'.docx');
    i+=2

This is the first document. I would like every document to have an output like this

This is the last document created, as you can see the information from the first document as well as the next 3 documents are all stacked and shown in the final output of this last document

1 个答案:

答案 0 :(得分:1)

重新排列您的代码:

os.chdir("C:\\Users\\user\\Desktop\\" +FolderName)
i=1
while i < 10:
    doc = Document()
    doc.add_paragraph('Title/Keyword:'+str(titles[i]));
    doc.add_paragraph('Research Link:'+str(link[i]));
    doc.add_paragraph('Target Site:'+str(keyword[i]));
    doc.save(str(doc_number[i])+str(essay_type[i])+' '+str(titles[i])+' '+str(writer[i])+'.docx');
    i+=2