day4-Python学习笔记(五)文件读写,文件内容修改

文件读写,文件内容修改

f.write()#只能写入字符串,效率更高

f.writelines()#能写循环对象(list,元组等)

# f =open('a.txt','w',encoding='utf-8')
# names = ['a','b','c']
# #for name in names:
# # f.write(name)
# s ='dinog,123456'+' '
# # fw = f.write(s)
# fe = f.writelines(s)
# f.flush()#立即把缓冲区里面的内容写到磁盘里面
# with open('a.txt','w') as fb,open('b.txt','w') as fb2:
# fb.write('hhh')
# fb2.writelines('nice')
#rb

#wb
#ab
# f = open('5.png','rb')#bytes,以二进制模式打开
# print(f.read())

#把网站上图片下载下来
# import requests
# url = 'http://www.nnzhp.cn/wp-content/uploads/2017/09/20170920072543_91700.png'
# img = requests.get(url).content
# f = open('hhh.jpg','wb')
# f.write(img)

文件修改
#字符串是不能被修改的
# with open('geci','a+',encoding='utf-8') as f:
# f.seek(0)
# all = f.read()
# new_all = all.replace('一','二')
# f.seek(0)
# f.truncate()
# f.write(new_all)
# f.flush()

import os
with open('geci','a+') as f,open('geci.bak','w') as f2:
f.seek(0)
for line in f:
new_line = line.replace('1','2')#修改文件内容
f2.write(new_line)

os.remove('geci')#删除旧文件
os.rename('geci.bak','geci')#把新文件改名成为旧文件



原文地址:https://www.cnblogs.com/flynn0825/p/8270679.html