在Python中替换文件内容可以通过以下几种方法实现:
方法一:使用 `str.replace()` 方法
def replace_content(file_path, old_content, new_content):读取文件内容with open(file_path, 'r', encoding='utf-8') as file:content = file.read()替换内容new_content = content.replace(old_content, new_content)写回文件with open(file_path, 'w', encoding='utf-8') as file:file.write(new_content)
方法二:使用 `fileinput` 包
import fileinputdef replace_content_inplace(file_path, old_str, new_str):with fileinput.FileInput(file_path, inplace=True, encoding='utf-8') as file:for line in file:print(line.replace(old_str, new_str), end='')
方法三:使用 `with` 语句和文件对象的 `write()` 方法

def replace_content_with_new_file(file_path, old_str, new_str, output_path):读取文件内容with open(file_path, 'r', encoding='utf-8') as file:content = file.read()替换内容new_content = content.replace(old_str, new_str)写入新文件with open(output_path, 'w', encoding='utf-8') as file:file.write(new_content)
方法四:使用 `os` 模块和文件重命名
import osdef replace_content_with_rename(file_path, old_str, new_str):临时文件名temp_file_path = file_path + '.tmp'读取文件内容并替换with open(file_path, 'r', encoding='utf-8') as infile, open(temp_file_path, 'w', encoding='utf-8') as outfile:for line in infile:outfile.write(line.replace(old_str, new_str))删除原文件并重命名临时文件os.remove(file_path)os.rename(temp_file_path, file_path)
