【问题标题】:Search and Replace not working in header? Python docx搜索和替换在标题中不起作用? Python 文档
【发布时间】:2012-07-24 09:03:21
【问题描述】:

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

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")

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

【问题讨论】:

  • 发布一些示例代码,以便我们更好地帮助您。你说我每次做“这个”……你是怎么做的?
  • 这样更好,现在错误的完整回溯是什么?
  • 这很奇怪......它没有回溯,运行良好。当我去目录查看示例文档时,它不会打开文档!
  • 尝试用notepad++之类的东西打开它,看看它是什么意思

标签: python search header replace docx


【解决方案1】:

我不知道这个模块,但一般来说你不应该就地编辑文件。打开文件“A”,写入文件“/tmp/A”。关闭这两个文件并确保没有错误,然后将“/tmp/A”移动到“A”。否则,如果在写入过程中出现问题,您可能会破坏文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2021-05-25
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多