How can one replace words in a text file using Python?
To replace words in a text file, you can use Python’s file handling operations and string replacement functions.
Here is an example code demonstrating how to replace words in a text file.
def replace_word(file_path, old_word, new_word):
# 打开文件并读取内容
with open(file_path, 'r') as file:
content = file.read()
# 使用replace函数替换单词
new_content = content.replace(old_word, new_word)
# 将替换后的内容写回文件
with open(file_path, 'w') as file:
file.write(new_content)
# 替换test.txt文件中的"old"为"new"
replace_word('test.txt', 'old', 'new')
In the code above, the replace_word function takes three parameters: the file path, the word to be replaced, and the word to replace it with.
The function first opens the file using the open function and reads the contents of the file into the variable content using the read method.
Next, use the replace method of the string to replace words in the content, and save the result in the variable new_content.
Finally, use the open function to reopen the file and use the write method to write the new_content into the file, achieving the replacement operation.
In the sample code, we set the file name as test.txt, the word to be replaced as old, and the word to replace it as new. You can modify these parameters based on your actual needs.