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)

 

转载于:https://www.cnblogs.com/louis-w/p/8267991.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值