在Python中修改文件内容可以通过以下几种方法实现:
直接修改原文件
使用`open`函数以读取模式(`r`)打开文件,读取内容后使用字符串的`replace`方法进行替换,最后以写入模式(`w`)将修改后的内容写回文件。
def replace_in_file(file_path, old_str, new_str):with open(file_path, 'r', encoding='utf-8') as file:file_data = file.read()updated_data = file_data.replace(old_str, new_str)with open(file_path, 'w', encoding='utf-8') as file:file.write(updated_data)
写入新文件
将原文件内容读取后,将修改后的内容写入到一个新文件中,然后删除原文件,并将新文件重命名为原文件名。
def replace_in_file_new(file_path, old_str, new_str):with open(file_path, 'r', encoding='utf-8') as file:file_data = file.read()updated_data = file_data.replace(old_str, new_str)with open(f'{file_path}.bak', 'w', encoding='utf-8') as file:file.write(updated_data)os.remove(file_path)os.rename(f'{file_path}.bak', file_path)

使用正则表达式
利用`re`模块中的`sub`方法进行更复杂的字符串替换。
import redef replace_with_regex(file_path, pattern, replacement):with open(file_path, 'r', encoding='utf-8') as file:file_data = file.read()updated_data = re.sub(pattern, replacement, file_data)with open(file_path, 'w', encoding='utf-8') as file:file.write(updated_data)
使用这些方法时,请确保文件路径正确,并且考虑到文件编码问题,可能需要指定`encoding`参数。完成文件操作后,不要忘记关闭文件。
