搜索和替换不在标头中工作? Python docx

时间:2012-07-25 20:28:12

标签: python search header replace docx

我正在使用python-docx模块对大量文档进行一些编辑。它们都包含一个标题,我需要在其中替换一个数字,但每次执行此操作时,文档都不会打开,并且内容不可读。任何人都有任何想法,为什么会发生这种情况,或者样本工作代码片段?感谢。

from docx import *
#document = yourdocument.docx
filename = "NUR-ADM-2001"
relationships = relationshiplist()
document = opendocx("C:/Users/ai/My Documents/Nursing docs/" + filename + ".docx")
docbody = document.xpath('/w:document/w:body',namespaces=nsprefixes)[0]
advReplace(docbody, "NUR-NPM 101", "NUR-NPM 202")


# Create our properties, contenttypes, and other support files
coreprops = coreproperties(title='Nursing Doc',subject='Policies',creator='IA',keywords='Policy'])
appprops = appproperties()
contenttypes = contenttypes()
websettings = websettings()
wordrelationships = wordrelationships(relationships)

# Save our document
savedocx(document,coreprops,appprops,contenttypes,websettings, wordrelationships,"C:/Users/ai/My Documents/Nursing docs/" + filename + ".docx")

编辑:所以它最终可以打开文档,但它说有些内容无法显示,标题已经消失了...想法?

1 个答案:

答案 0 :(得分:0)

我不知道这个模块,但一般情况下你不应该编辑文件。打开文件" A",写文件" / tmp / A"。关闭这两个文件并确保没有错误,然后移动" / tmp / A"到" A"。否则,如果在写入期间出现问题,您可能会冒失败文件。