Objective
Develop a Python program that reads a text file, replaces specified words, and saves the modified content into a new file.
The program should accept the filename, the target word, and the replacement word as command-line parameters:
Example command:
replace_text file.txt hello goodbye
The output will be saved in a file named "file.txt.out", where every instance of "hello" is replaced with "goodbye".
Example Python Exercise
Show Python Code
import sys
def replace_text_in_file(file_name, target_word, replacement_word):
"""
Reads a text file, replaces all occurrences of the target word with the replacement word,
and saves the modified content into a new file named 'file_name.out'.
Parameters:
file_name (str): The name of the input file to read.
target_word (str): The word to be replaced.
replacement_word (str): The word to replace the target word with.
"""
try:
# Open the input file in read mode
with open(file_name, 'r') as file:
# Read all the lines from the file
content = file.read()
# Replace all occurrences of target_word with replacement_word
modified_content = content.replace(target_word, replacement_word)
# Create the output file name by appending '.out' to the original file name
output_file_name = file_name + '.out'
# Open the output file in write mode and save the modified content
with open(output_file_name, 'w') as output_file:
output_file.write(modified_content)
print(f"Modification successful! The modified content has been saved to '{output_file_name}'")
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Main program execution
if __name__ == "__main__":
# Check if the correct number of arguments are provided
if len(sys.argv) != 4:
print("Usage: replace_text ")
else:
# Extract command-line arguments
file_name = sys.argv[1]
target_word = sys.argv[2]
replacement_word = sys.argv[3]
# Call the replace_text_in_file function
replace_text_in_file(file_name, target_word, replacement_word)
Output
Assume file.txt contains the following text:
hello world
hello there
hello again
If you run the following command:
python replace_text.py file.txt hello goodbye
The program will create a new file, file.txt.out, with the following content:
goodbye world
goodbye there
goodbye again
Share this Python Exercise