简体   繁体   English

使用python读取和写入.docx文件

[英]Read and Write .docx file with python

I have a folder containing several .docx files with names [Code2001.docx, Code2002.docx... Code2154.docx] .我有一个文件夹,其中包含多个名称为[Code2001.docx, Code2002.docx... Code2154.docx] .docx文件。

I'm trying to write a script that will:我正在尝试编写一个脚本,它将:

  1. Open each .docx file打开每个 .docx 文件
  2. Append one line to the document;在文档中追加一行; "This is checked" “这是检查”
  3. Save the .docx-file to another folder, named "Code2001_checked"将 .docx 文件保存到另一个名为“Code2001_checked”的文件夹中

After searching I've only managed to get the filename with the loop:搜索后,我只设法通过循环获取文件名:

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

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

I also found this: docx module but the documentation is poor to continue.我还发现了这个: docx 模块,但文档很差,无法继续。

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.'))

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.要完成此操作,您将需要使用 savedocx() 函数,并且在项目的根目录中有一个使用示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM