# 方式一 文件编辑器用的方式
with open('文件路径', mode='rt', encoding='utf-8') as f:
res = f.read()
print(res)
data = res.replace('华王', '王华')
print(data)
with open('文件路径',mode='wt',encoding='utf-8') as f1:
f1.write(data)
# 用不占内存的方式修改文件
with open('a.txt',mode='rt',encoding='utf-8') as f,\
open('.c.txt.swap',mode = 'wt',encoding='utf-8') as f2:
for line in f:
f2.write(line.replace('王华','华王'))
os.remove('a.txt')
os.rename('.c.txt.swap','a,txt')
文件替换技巧
本文介绍两种在Python中替换文件内容的方法。第一种使用内存加载整个文件并进行替换,第二种采用逐行读取写入临时文件的方式,适用于大文件处理,避免内存溢出。
2131

被折叠的 条评论
为什么被折叠?



