26.Python:文件修改的两种方式
时间:2021-06-25 17:21:16
收藏:0
阅读:0
# 方式一:文本编辑器的方式
# with open(‘a.txt‘, mode=‘rt‘, encoding=‘utf-8‘) as f1:
# res = f1.read()
# data = res.replace(‘a1‘, ‘b1‘)
#
# with open(‘a.txt‘, mode=‘wt‘, encoding=‘utf-8‘) as f2:
# f2.write(data)
# 方式二
import os
with open(‘a.txt‘, mode=‘rt‘, encoding=‘utf-8‘) as f1, \
open(‘b.txt‘, mode=‘wt‘, encoding=‘utf-8‘) as f2:
for line in f1:
f2.write(line.replace(‘a1‘, ‘b1‘))
os.remove(‘a.txt‘)
os.rename(‘b.txt‘, ‘a.txt‘)
评论(0)