Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

ms word - Read and Write .docx file with python

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. Open each .docx file
  2. Append one line to the document; "This is checked"
  3. Save the .docx-file to another folder, named "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

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

Any suggestions on how to finish this script?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...