Replace Words in a File in Python
To replace words in a file in Python, we can read the file’s content, modify the text using the replace()
method or regular expressions, and then write the modified content back to the file. This ensures that all occurrences of a specific word are replaced efficiently.
Examples
1. Replacing a Word in a Text File
In this example, we replace a specific word in a text file using the replace()
method.
# Define the file name
file_name = "sample.txt"
# Read the file content
with open(file_name, "r") as file:
content = file.read()
# Replace occurrences of the word "old" with "new"
modified_content = content.replace("old", "new")
# Write the modified content back to the file
with open(file_name, "w") as file:
file.write(modified_content)
print("Word replacement completed successfully.")
sample.txt
The old house at the end of the street had a mysterious charm.
He found an old photograph of his grandparents in a dusty album.
My old laptop is slow, but it still works for basic tasks.
Explanation
Here’s how this program works:
open(file_name, "r")
: Opens the file in read mode and reads its content.content.replace("old", "new")
: Replaces all occurrences of “old” with “new” in the file content.open(file_name, "w")
: Opens the file in write mode and writes the modified content back.
Output

sample.txt is modified with the replacements.
The new house at the end of the street had a mysterious charm.
He found an new photograph of his grandparents in a dusty album.
My new laptop is slow, but it still works for basic tasks.
2. Replacing Multiple Words in a File
In this example, we replace multiple words in a file using a dictionary and the replace()
method.
# Define the file name
file_name = "sample.txt"
# Dictionary of words to replace
replacements = {"old": "new", "Python": "JavaScript", "error": "issue"}
# Read the file content
with open(file_name, "r") as file:
content = file.read()
# Replace words using dictionary
for old_word, new_word in replacements.items():
content = content.replace(old_word, new_word)
# Write the modified content back to the file
with open(file_name, "w") as file:
file.write(content)
print("Multiple word replacement completed.")
sample.txt
The old man found an old book in his old library.
Learning Python is fun, but Python can sometimes throw an unexpected error.
An error in the code caused a major error during execution.
Explanation
We use a dictionary to store multiple word replacements:
replacements
: A dictionary where keys are old words and values are new words.for old_word, new_word in replacements.items()
: This For loop iterates through the dictionary and replaces each word.open(file_name, "w")
: Saves the modified content back to the file.
Output
Multiple word replacement completed.

sample.txt is modified with the replacements.
The new man found an new book in his new library.
Learning JavaScript is fun, but JavaScript can sometimes throw an unexpected issue.
An issue in the code caused a major issue during execution.
3. Replacing Words Case-Insensitively Using Regular Expressions
To perform case-insensitive word replacement, we use the re.sub()
function from the re
module.
import re
# Define the file name
file_name = "sample.txt"
# Read the file content
with open(file_name, "r") as file:
content = file.read()
# Replace "old" with "new" in a case-insensitive manner
modified_content = re.sub(r"old", "new", content, flags=re.IGNORECASE)
# Write the modified content back to the file
with open(file_name, "w") as file:
file.write(modified_content)
print("Case-insensitive word replacement completed.")
sample.txt
The OLD man lived in an old house with his old dog.
An olD book was placed on an oLD wooden shelf.
He always preferred OLD-school methods over modern ones.
Explanation
re.sub(r"old", "new", content, flags=re.IGNORECASE)
: Replaces “old” with “new” regardless of case.- The
re.IGNORECASE
flag ensures that “OLD”, “Old”, and “old” are all replaced.
Output
Case-insensitive word replacement completed.

sample.txt is modified with the replacements.
The new man lived in an new house with his new dog.
An new book was placed on an new wooden shelf.
He always preferred new-school methods over modern ones.
4. Replacing Words in a File and Saving a Backup
Before replacing words, we save a backup of the original file to prevent accidental loss of data.
import shutil
# Define the file name
file_name = "sample.txt"
backup_file = "sample_backup.txt"
# Create a backup of the original file
shutil.copy(file_name, backup_file)
# Read the file content
with open(file_name, "r") as file:
content = file.read()
# Replace words
modified_content = content.replace("old", "new")
# Write the modified content back to the file
with open(file_name, "w") as file:
file.write(modified_content)
print(f"Word replacement completed. Backup saved as {backup_file}.")
Explanation
shutil.copy(file_name, backup_file)
: Creates a backup before modifying the file.content.replace("old", "new")
: Replaces the search string “old” with the replacement string “new”.
Output
Word replacement completed. Backup saved as sample_backup.txt.
Conclusion
In this tutorial, we covered various ways to replace words in a file in Python, including:
- Basic word replacement using
replace()
. - Replacing multiple words using a dictionary.
- Case-insensitive replacement using regular expressions.
- Saving a backup before modifying the file.