sdszz1996 发表于 2020-5-8 00:29:23

新人求助关于python-docx的问题

from docx import Document

doc = Document('test.docx')
name = str(input('请输入'))
IDcard = str(input('请输入'))
paragraph3 = doc.paragraphs

paragraph3.add_run(name).underline = True
paragraph3.add_run(IDcard).underline = True

paragraph3.runs = paragraph3.runs
paragraph3.runs = paragraph3.runs

paragraph3.runs.clear()
paragraph3.runs.clear()

doc.save('new.docx')

大佬们,为什么我这段代码创建了新的文档后和原文档一样呢
我想把paragraph3.runs的内容替换为paragraph3.runs的内容
为什么不能用 = 呢

zltzlt 发表于 2020-5-8 07:50:59

paragraph3.runs = paragraph3.runs 这一句相当于将 paragraph3.runs 指向 paragraph3.runs ,它们都是指向同一个数据,所以对其中一个执行了 clear(),另外一个也会被 clear()

txxcat 发表于 2020-5-8 09:12:23

from docx import Document

doc = Document('test.docx')
name = str(input('请输入'))
IDcard = str(input('请输入'))
paragraph3 = doc.paragraphs

paragraph3.add_run(name).underline = True
paragraph3.add_run(IDcard).underline = True


doc.paragraphs.text = doc.paragraphs.text
doc.paragraphs.text = doc.paragraphs.text

doc.paragraphs.clear()
doc.paragraphs.clear()

doc.save('new.docx')
页: [1]
查看完整版本: 新人求助关于python-docx的问题