4

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:......\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.

Any suggestions on how to finish this script?

Jir
  • 2,985
  • 8
  • 44
  • 66
  • 2
    Why not simply rename (move) them? If the name is changed then you know it was checked. `docx` isn't the easiest format to work with, especially if not from scratch with that library you mention. – CrystalDuck Jul 12 '13 at 13:18
  • 1
    unfortunately i must write one line inside the .docx file – Stavros Anastasiadis Jul 12 '13 at 13:23
  • What is wrong with the documentation for python-docx? Which part is causing you trouble? – Tim Pietzcker Jul 12 '13 at 13:26
  • Well that library will certainly help - just read the built-in documentation. Looks like the methods `opendocx`, `paragraph`, and `savedocx` will be useful. You might need to use the XML tree from what I can see at a glance. – CrystalDuck Jul 12 '13 at 13:31
  • Once you've installed the library, in the python interpreter you can import it and use `help(docx)` to see the built-in documentation. – CrystalDuck Jul 12 '13 at 13:32
  • I am not a experienced python user and no example are provided – Stavros Anastasiadis Jul 12 '13 at 13:38

1 Answers1

6
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.

Sam Barani
  • 281
  • 1
  • 4
  • After the helpfull post from Sam Barami, i finnally got my code running. – Stavros Anastasiadis Jul 13 '13 at 12:36
  • 3
    You should avoid using `import *` if you can: [https://docs.python.org/2/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module](https://docs.python.org/2/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module) – LMc Oct 24 '16 at 15:23