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') # 文件改名
posted @ 2018-01-09 14:30  王思磊  阅读(112)  评论(0编辑  收藏  举报