Skip to content

Instantly share code, notes, and snippets.

@A2va
Last active November 2, 2021 21:05
Show Gist options
  • Save A2va/585e3898939d4c2123da8d038c7919ad to your computer and use it in GitHub Desktop.
Save A2va/585e3898939d4c2123da8d038c7919ad to your computer and use it in GitHub Desktop.
Enable modification of all word document into the actual path
import os
import zipfile
import tempfile
import shutil
folder = 'path/to/folder'
for dirpath, dirnames, filenames in os.walk(folder):
for filename in [f for f in filenames if f.endswith(".docx")]:
full_path = os.path.join(dirpath, filename)
with zipfile.ZipFile(full_path,mode='r') as file_zip:
file=file_zip.open("word/settings.xml")
tmp_dir = tempfile.mkdtemp()
text=file.read()
text=text.decode('utf-8')
text=text.replace('w:enforcement="true"','w:enforcement="false"')
file_zip.extractall(tmp_dir)
with open(os.path.join(tmp_dir,'word/settings.xml'), 'w') as f:
f.write(text)
filenames = file_zip.namelist()
file.close()
zip_copy_filename = full_path
with zipfile.ZipFile(zip_copy_filename, "w") as docx:
for filename in filenames:
docx.write(os.path.join(tmp_dir,filename), filename)
# Clean up the temp dir
shutil.rmtree(tmp_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment