使用python读取和写入.docx文件 [英] Read and Write .docx file with python

查看:46
本文介绍了使用python读取和写入.docx文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a folder containing several .docx files with names [Code2001.docx, Code2002.docx... Code2154.docx].

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

I'm trying to write a script that will:

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

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

After searching I've only managed to get the filename with the loop:

import os
os.chdir(r"E:......	est")

for files in os.listdir("."):
    if files.endswith(".docx"):
        print filename

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

I also found this: docx module but the documentation is poor to continue.

关于如何完成这个脚本有什么建议吗?

Any suggestions on how to finish this script?

推荐答案

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

根据您要在文件中附加文本的位置,可能需要更改第二行.要完成此操作,您将需要使用 savedocx() 函数,并且在项目的根目录中有一个使用示例.

The second line may need to chance depending on where in the file you are going to append the text. To finish this, you will need to use the savedocx() function, and there is an example of its usage in the root of the project.

这篇关于使用python读取和写入.docx文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆