How can Python batch replace characters in files?
In Python, the fileinput module can be used to perform batch replacement of characters in a file. Here is an example code for replacing characters in a file:
import fileinput
# 定义替换的函数
def replace_text(file_path, old_text, new_text):
# 使用fileinput替换文件中的字符
with fileinput.FileInput(file_path, inplace=True, backup='.bak') as file:
for line in file:
# 替换字符并输出到文件
print(line.replace(old_text, new_text), end='')
# 替换文件中的字符
file_path = 'example.txt'
old_text = 'old'
new_text = 'new'
replace_text(file_path, old_text, new_text)
In this example, we have defined a replace_text function that takes a file path, the character to replace, and the new character as parameters. The function uses fileinput.FileInput to open the file with inplace parameter set to True, so the output content will be written directly to the file. The backup parameter is set to .bak, indicating that a backup of the original file will be created before the replacement. Next, we iterate through each line in the file, replace the character using the replace method, and write it back to the file.
Before running the code, make sure you have installed the fileinput module. You can install it using the following command:
pip install fileinput