Python--文件修改

第一种

# with open('geci.txt', 'a+') as f:
# f.seek(0)
# all1 = f.read()
# new_all = all1.replace('读', '想')
# f.seek(0)
# f.truncate()
# f.write(new_all)
# f.flush()

第二种

import os


with open('geci.txt', 'a+') as f, open('gecibak.txt', 'w') as f1:
f.seek(0)
for line in f:
new_line = line.replace('读', '想')
f1.write(new_line)

os.remove('geci.txt') # 删除文件
os.rename('gecibak.txt', 'geci.txt') # 文件改名
原文地址:https://www.cnblogs.com/wangsilei/p/8251299.html