DEV Community


Search and Replace Text in Microsoft Word Document using Python

tilalahmad profile image Tilal Ahmad Sana ・2 min read

If you are automating MS Word documents with Python, then you know that search and replace placeholders/text in documents is a key feature of automation. In this tutorial, I will show you how easily you can add search and replace text feature in your application.

We will use Aspose.Words Cloud SDK for Python for the purpose. You can use Aspose.Words REST API to create a new Word document from scratch, edit, split, merge, compare and convert existing Word documents, but we will only focus on search and replace feature in this tutorial. So let’s start.
Here are the Steps to Search and Replace Text in a Word document:

Step 1:
Sign up with and get App SID and App Key to authenticate your rest API calls.

Step 2:
Install Aspose.Words Cloud SDK for Python from PIP.

Step 3:
Copy and paste the following code into your Python script file. Put your source file in the same directory, amend the Python script as per your file and run. That’s it.

# For complete examples and data files, please go to
import asposewordscloud
import asposewordscloud.models.requests
from shutil import copyfile

api_client = asposewordscloud.ApiClient() = ''
# Please get your App Key and App SID from
api_client.configuration.api_key['api_key'] = 'xxxxxxxxxxxxxxxxxxxxxx' # Put your appKey here
api_client.configuration.api_key['app_sid'] = 'xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx' # Put your appSid here

words_api = asposewordscloud.WordsApi(api_client)
filename = 'C:/Temp/TestFile.docx'
remoteFileName = 'TestFile.docx'
outputFileName = 'TestFile_output.docx'

#upload DOCX file to storage
request_upload = asposewordscloud.models.requests.UploadFileRequest(filename,remoteFileName)
response_upload = words_api.upload_file(request_upload)

#Search and Replace the Text
requestReplaceText = asposewordscloud.ReplaceTextParameters(old_value='malesuada', new_value='aspose')
request = asposewordscloud.models.requests.ReplaceTextRequest(name=remoteFileName, replace_text=requestReplaceText, dest_file_name=outputFileName)
result = words_api.replace_text(request)

#download file
response_download = words_api.download_file(request_download)
copyfile(response_download, 'C:/Temp/'+ outputFileName)
print("Result {}".format(result))

Hope this helps. If you have any question or suggestion, please feel free to comment here or Aspose.Words Cloud forum.

Discussion (0)

Editor guide