文件读取之b模式

1.模式介绍

t:
   1、读写都是以字符串(unicode)为单位
   2、只能针对文本文件
   3、必须指定字符编码,即必须指定encoding参数
b:binary模式
   1、读写都是以bytes为单位
   2、可以针对所有文件
    3、一定不能指定字符编码,即一定不能指定encoding参数
总结:
1、在操作纯文本文件方面t模式帮我们省去了编码与解码的环节,b模式则需要手动编码与解码,所以此时t模式更为方便
2、针对非文本文件(如图片、视频、音频等)只能使用b模式

文本格式也可以使用b模式

with open(r'd.txt',mode='rb') as f:
    res=f.read() # d文件中的内容的utf-8编码下的二进制
   print(res,type(res))
# b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88a'
<class 'bytes'>
    print(res.decode('utf-8')) # 将内容重新以utf-8的格式                               # 解码

文件的拷贝

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)
   # 使用for循环会降低内存占用

文件的循环读取

1.while循环(可以控制自己每次读取的数据量)

with open(r'test.jpg',mode='rb') as f:
    while True:
        res=f.read(1024) # 1024
        if len(res) == 0:
            break
        print(len(res))

2.for循环(以行为单位,一行的内容过长时会导致一次性读入内存的数据过大)

with open(r'g.txt',mode='rt',encoding='utf-8') as f:
    for line in f:
        print(line)
with open(r'g.txt',mode='rb') as f:
    for line in f:
        print(line.decode('utf-8'))

两者效果相同

posted @ 2020-03-21 19:54  江湖有梦  阅读(396)  评论(0编辑  收藏  举报