How can Python replace a specific character in a file?

One way to replace a character in a file is by using Python’s file manipulation functions.

# 打开文件并读取内容
with open('file.txt', 'r') as file:
    content = file.read()

# 替换字符
new_content = content.replace('old_char', 'new_char')

# 将替换后的内容写入文件
with open('file.txt', 'w') as file:
    file.write(new_content)

This code will open a file named file.txt, read its content, and replace all occurrences of old_char with new_char. Finally, it will write the modified content back to the original file.

Please replace file.txt with the path of the file you want to work with. Also, replace old_char with the character you want to replace, and new_char with the character you want to replace it with.

bannerAds