ⅩⅡ:文件的操作模式---x模式和b模式

一.x模式

  • x模式(控制文件操作的模式)=》了解
  • x,只写模式【不可读;不存在则创建,存在则报错】
# 演示1:
with open('a.txt',mode='x',encoding='utf-8') as f:
    pass     # =》 增加新空文件'a.txt'
# 演示2:
with open('c.txt',mode='x',encoding='utf-8') as f:
    f.read()    # =》 增加新空文件'c.txt',报错
# 演示3:
with open('d.txt',mode='x',encoding='utf-8') as f:
    f.write('哈哈哈\n')   # =》 增加新文件'd.txt'内容为'哈哈哈'

二.b模式

控制文件读写内容的模式:

t模式:

  • 读写都是以字符串(unicode)为单位
  • 只能针对文本文件
  • 必须指定字符编码,即必须指定encoding参数

b模式:(binary模式)

  • 读写都是以bytes为单位
  • 可以针对所有文件
  • 一定不能指定字符编码,即不能指定encoding参数

总结:

  • 在操作纯文本文件方面t模式帮我们省去了编码与解码的环节,b模式则需要手动编码与解码,所以此时t模式更为方便
  • 针对非文本文件(如图片、视频、音频等)只能使用b模式

错误演示:

# t模式只能读文本文件:
with open(r'爱nmlgb的爱情.mp4',mode='rt') as f:
     f.read()    # 硬盘的二进制读入内存-》t模式会将读入内存的内容进行decode解码操作

正确演示:

# 演示1:
with open(r'test.jpg',mode='rb',encoding='utf-8') as f:
    res=f.read() # 硬盘的二进制读入内存—>b模式下,不做任何转换,直接读入内存
    print(res) # bytes类型—》当成二进制
    print(type(res))

# 演示2:
with open(r'd.txt',mode='rb') as f:
    res=f.read() # utf-8的二进制
    print(res,type(res))

    print(res.decode('utf-8'))

# 演示3:
with open(r'd.txt',mode='rt',encoding='utf-8') as f:
    res=f.read() # utf-8的二进制->unicode
    print(res)

# 演示4:
with open(r'e.txt',mode='wb') as f:
    f.write('你好hello'.encode('gbk'))

# 演示5:
with open(r'f.txt',mode='wb') as f:
    f.write('你好hello'.encode('utf-8'))
    f.write('哈哈哈'.encode('gbk'))

文件拷贝工具:

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)

循环读取文件:

# 方式一:自己控制每次读取的数据的数据量(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))
# 方式二:以行为单位读,当一行内容过长时会导致一次性读入内容的数据量过大
# t模式:
with open(r'g.txt',mode='rt',encoding='utf-8') as f:
    for line in f:
        print(len(line),line)

# b模式读文本:
with open(r'g.txt',mode='rb') as f:
    for line in f:
        print(line)

# b模式读图片/视频:
with open(r'test.jpg',mode='rb') as f:
    for line in f:
        print(line)
posted @ 2020-03-16 15:13  迷路的玖儿  阅读(622)  评论(0)    收藏  举报