首页 > 其他 > 详细

复习文件操作

时间:2019-12-23 23:26:29      阅读:84      评论:0      收藏:0      [点我收藏+]
#文件内容替换操作
import os
old_str = ‘不要回答!‘
new_str = ‘绝对不能回答!‘
f = open(‘test_file‘,‘r‘,encoding=‘utf-8‘)
new_f = open(‘file_new‘,‘w‘,encoding=‘utf-8‘)
for i in f:
if old_str in i:
new_line = i.replace(old_str,new_str)
else:
new_line = i
new_f.write(new_line)
f.close()
new_f.close()
os.replace(‘file_new‘,‘test_file‘)

#在文件里加新加一行内容内容不影响其他内容
import os
file = open(‘test_file‘,‘r‘,encoding=‘utf-8‘)
content = file.readlines()
content.insert(5,‘welcome to nice_xm\n‘)
file_new = open(‘new_file‘,‘w‘,encoding=‘utf-8‘)
content = ‘‘.join(content)
print(content)
file_new.write(content)
file.close()
file_new.close()
os.replace(‘new_file‘,‘test_file‘)

复习文件操作

原文:https://www.cnblogs.com/xiaolang666/p/12088564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!