使用python读写.docx文件

Sta*_*dis 2 python ms-word python-docx

我有一个文件夹,其中包含几个带有名称的.docx文件[Code2001.docx, Code2002.docx... Code2154.docx].

我正在尝试编写一个脚本:

  1. 打开每个.docx文件
  2. 在文档中附加一行; "这是检查"
  3. 将.docx文件保存到另一个名为"Code2001_checked"的文件夹中

搜索后,我只是设法获得循环文件名:

import os
os.chdir(r"E:......\test")

for files in os.listdir("."):
    if files.endswith(".docx"):
        print filename
Run Code Online (Sandbox Code Playgroud)

我也发现了这个:docx模块,但文档很难继续.

有关如何完成此脚本的任何建议?

小智 5

from docx import *
document = opendocx("document.doc")
body = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
body.append(paragraph('Appending this.'))
Run Code Online (Sandbox Code Playgroud)

第二行可能需要偶然,具体取决于您要在文件中追加文本的位置.要完成此操作,您需要使用savedocx()函数,并且在项目的根目录中有一个使用示例.

  • 你应该避免使用`import*`:[https://docs.python.org/2/faq/programming.html#what-are-the-best-practices-for-using-import-in-a - 模(https://docs.python.org/2/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module) (2认同)