Python基础学习四 文件操作(二)
####读取文件####
with open('goods_info.txt', 'r', encoding='utf-8') as f:
f.seek(0) # 注意指针位置
goods_info = eval(f.read()) # eval()将字符串str当成有效的表达式来求值并返回计算结果
####内容替换####
with open('123.txt','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('123.txt',encoding='utf-8') as f,open('333.txt','w',encoding='utf-8') as f2:
for line in f:
new_line = line.replace('一','二')
f2.write(new_line)
os.remove('123.txt')#删文件
os.rename('123.txt','333')#改名
###图片读写#####
在博客上,上传一张图片,保存图片的URL
import requests
url = 'https://images2017.cnblogs.com/blog/1297828/201801/1297828-20180111115848004-1702177202.jpg'
img = requests.get(url).content
f = open('123.jpg','wb')# bytes ,以二进制模式打开
f.write(img)