[英]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.我有两个列表,想要 append 它们的值作为“a----------------b”到“docxpy.docx”文件中。 But every single time it appends only one of them.
但是每次它只附加其中一个。 I am new to python please font make fun of me
我是新来的 python 请字体取笑我
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.问题是您在循环内初始化了
document
,这意味着每次迭代都会使用空Document()
object 重新初始化document
。结果,在循环的最后一次迭代中,您最终得到的文档只包含最后一对a,b
,这就是为什么您在 output 文档中只看到一行的原因。 Initializing the document
variable before the for loop should do the trick.在 for 循环之前初始化
document
变量应该可以解决问题。
In addition, you should put the save
method call after the loop.此外,您应该将
save
方法调用放在循环之后。 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.这不是绝对必要的(您会注意到无论哪种方式都会得到相同的结果),但它可以节省时间/资源,因为一旦添加了所有段落,您只需要在最后将文件写入磁盘一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.