How to add tracked change to xml in docx file programatically

matsuo_basho 30 Reputation points
2025-04-18T21:12:21.89+00:00

My goal is to programmatically manipulate the document.xml file of a docx word document in order to create a new word document with tracked changes.

I've attempted to do this using Python's native xml.etree.ElementTree module. The script I've written runs, but when I try to open the resultant word document, I get an error saying that the file couldn't be opened.

I would prefer to stay in Python, but open to any language that gets the job done. I don't know if the problem is in the part of the code where I save the zipfile with the new xml. Somewhere on SO I saw that the files need to be saved from the terminal as an admin. As you see below, I'm not doing that here:

with zipfile.zipFile(output_path, 'w') as new_zipf:
    new zipf.writestr(doc_xml, ET.tostring(root, encoding='utf-8', xml_declaration=True)
    
    for item in zipf.namelist():
        if item != doc_xml:
            new_zipf.writestr(item, zipf.read(item))
Word Management
Word Management
Word: A family of Microsoft word processing software products for creating web, email, and print documents.Management: The act or process of organizing, handling, directing or controlling something.
999 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.