Updating fields requires using the Word application itself via COM (Component Object Model) objects.
You're looking for the Fields.Update
method See: https://docs.microsoft.com/en-us/office/vba/api/word.fields.update.
The below should be the python equivalent of CTRL+A F9 from withing the Word GUI.
Code Snippet:
import sys
import os
import comtypes.client
filepath = '' # put file path here
word = comtypes.client.CreateObject('Word.Application') # opens the word application
doc = word.Documents.Open(filepath) # opens the specified file
doc.Fields.Update() # updates field, returns 0 if successful
doc.Save()
word.Quit()
Sample Function:
import sys
import os
import comtypes.client
def update_fields(filepath):
folder, filename = os.path.split(filepath)
extension = os.path.splitext(filename)[1]
acceptable_ext = ['.doc','.docx']
word = comtypes.client.CreateObject('Word.Application') # opens the word application
if extension not in acceptable_ext:
print('Error: Incorrect Filetype ' + extension)
else:
doc = word.Documents.Open(filepath) # opens the specified file
response = doc.Fields.Update() # updates field, returns 0 if successful
if response != 0:
print('Error with ' + filename + ' on field at Index '+str(response))
if response == 0:
doc.Save(NoPrompt=True, OriginalFormat=1)
print('Success with ' + filename)
doc.Close()
word.Quit()
filepath = '' # put path here
update_fields(filepath)
Sample Function with many documents:
import sys
import os
import comtypes.client
def update_fields(filepath):
folder, filename = os.path.split(filepath)
extension = os.path.splitext(filename)[1]
acceptable_ext = ['.doc','.docx']
word = comtypes.client.CreateObject('Word.Application') # opens the word application
if extension not in acceptable_ext:
print('Error: Incorrect Filetype ' + extension)
else:
doc = word.Documents.Open(filepath) # opens the specified file
response = doc.Fields.Update() # updates field, returns 0 if successful
if response != 0:
print('Error with ' + filename + ' on field at Index '+str(response))
if response == 0:
doc.Save(NoPrompt=True, OriginalFormat=1)
print('Success with ' + filename)
doc.Close()
word.Quit()
filepaths = [] # put list of paths here
for filepath in filepaths:
update_fields(filepath)