26.Python:文件修改的两种方式


# 方式一:文本编辑器的方式
# 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')
posted @ 2021-06-25 13:44  SEPIA  阅读(153)  评论(0)    收藏  举报