使用python读写.docx文件

时间:2013-07-12 12:54:35

标签: python ms-word python-docx

我有一个文件夹,其中包含多个名为[Code2001.docx, Code2002.docx... Code2154.docx] .docx 文件。

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

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

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

    import os
    os.chdir(r"E:......\test")
    
    for files in os.listdir("."):
        if files.endswith(".docx"):
            print filename
    

    我也发现了这个:docx module但是文档很难继续。

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

1 个答案:

答案 0 :(得分:5)

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

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

相关问题