在Python中,修改代码后保存的常见方法有:
使用文件保存功能
在Python编辑器中,选择“文件” -> “保存”或使用快捷键`Ctrl + S`或`Command + S`进行保存。
使用命令行
可以使用命令行将代码保存到文件中,例如使用`python code.py > output.txt`将代码保存到名为`output.txt`的文件中。
修改原文件
可以定义一个函数,如`alter`函数,用于读取文件内容,替换特定字符串,然后写回文件。
def alter(file, old_str, new_str):
with open(file, 'r', encoding='utf-8') as f:
file_data = f.read()
file_data = file_data.replace(old_str, new_str)
with open(file, 'w', encoding='utf-8') as f:
f.write(file_data)
alter('file1', '09876', 'python')
将内容写入新文件
可以将原文件内容和新修改的内容一起写入一个新的文件中,然后删除原文件,将新文件重命名为原文件名。
import os
def alter(file, old_str, new_str):
with open(file, 'r', encoding='utf-8') as f1, open(f'{file}.bak', 'w', encoding='utf-8') as f2:
f2.write(f1.read().replace(old_str, new_str))
os.remove(file)
os.rename(f'{file}.bak', file)
alter('file1', '09876', 'python')
使用`with open`语句
可以使用`with open`语句以读写模式打开文件,修改内容后直接保存,无需关闭文件。
with open('a.txt', 'r') as r:
txt = r.read()
txt = 'xxxxx' 修改内容
with open('a.txt', 'w') as w:
w.write(txt) 保存修改后的内容
选择适合你需求的方法进行保存即可