• 文件读取之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'xe5x93x88xe5x93x88xe5x93x88a'
    <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'))

    两者效果相同

  • 相关阅读:
    AQS简介
    原子类案例
    保证线程安全的三个方面
    CAS无锁机制
    乐观锁与悲观锁
    读写锁简介
    重入锁简介
    并发队列Queue
    报错Cannot resolve com.mysq.jdbc.Connection.ping method. Will use 'SELECT 1' instead 问题记录
    Springboot中MyBatis 自动转换 map-underscore-to-camel-case
  • 原文地址:https://www.cnblogs.com/bailongcaptain/p/12541691.html
Copyright © 2020-2023  润新知