一、x模式与b模式
1、x模式(了解)
x模式是控制文件操作的模式,是一种只写模式
特性:只能写、不可读;所写文件不存在则创建,存在就会报错。
例:
with open('a.txt',mode='x',encoding='utf-8') as f:
pass #a不存在,创建a.txt空文件
with open('a.txt',mode='x',encoding='utf-8') as f:
pass #a存在,报错
with open('b.txt',mode='x',encoding='utf-8') as f:
pass #b不存在,创建b.txt空文件
f.read() #x是只写模式,不支持读操作,所以报错
with open('c.txt',mode='x',encoding='utf-8') as f:
f.write('哈哈哈\n') #c不存在,创建b.txt文件,写入'哈哈哈\n'
2、b模式
1、b模式与t模式对比
t:
1)是控制文件读写内容的模式
2)读写都是以字符串(unicode)为单位
3)只能针对文本文件
4)必须指定字符编码,即必须指定encoding参数
b:
1)是控制文件读写内容的模式
2)读写都是以bytes为单位
3)可以针对所有文件
4)一定不能指定字符编码,即一定不能指定encoding参数
对比总结:
1)在操作纯文本文件方面t模式帮我们省去了编码与解码的环节,b模式则需要手动编码与解码,所以此时t模式更为方便,纯文本文件推荐使用t模式
2)针对非文本文件(如图片、视频、音频等)只能使用b模式,b模式兼容性强
2、b模式必须与r、w、b组合一起的基本使用
1、rb
with open(r'美图.jpg',mode='rb',encoding='utf-8') as f:
res=f.read() # utf-8的二进制->unicode
print(res)
2、wb
with open(r'e.txt',mode='wb') as f:
f.write('雷猴啊!hello'.encode('utf-8'))
3、ab
with open(r'e.txt',mode='ab') as f:
f.write('雷猴啊!hello'.encode('utf-8'))
2、b模式实用案例
# rb和wb写成的文件拷贝工具
src_file=input('源文件路径>>: ').strip()
dst_file=input('源文件路径>>: ').strip()
with open(r'{}'.format(src_file),mode='rb') as f1,\
open(r'{}'.format(dst_file),mode='wb') as f2:
# res=f1.read() # 内存占用过大
# f2.write(res)
for line in f1:
f2.write(line) #一次只读写一行
3、b模式循环取值
方式一:自己控制每次读取的数据的数据量
with open(r'美图.jpg',mode='rb') as f:
while True:
res=f.read(1024) # 自定义每次循环读取的字节数为1024
if len(res) == 0:
break #文件读完最后一行后,len长度为0,退出循环
print(len(res))
方式二:
(直接以行为单位读,当一行内容过长时会导致一次性读入内容的数据量过大)
with open(r'美图.jpg',mode='rb') as f:
for line in f: #用for循环每次只读一行
print(line)