🍖文件打开模式 "b"

文件打开模式 " b "

  • t 模式类似 ,但不能单独使用,必须是 rb,wb,ab
  • b 模式下读写都是以bytes单位的 字节模式
  • b 模式下一定不能指定 encoding 参数
  • 读写文件都是以bytes为单位,不需要指定字符编码,可以读写任意类型的文件

1、r b 模式

with open('1.jpg',mode='rb',) as f:   #不能添加encoding参数
    l=f.read()
    print(l)
    print(type(l))

with open('db.txt',mode='rb',) as f:
    l=f.read() 
    print(l.decode('utf-8'))          #bytes 类型需要解码
    print(type(l))

2、w b 模式

🍉用什么编码写就用什么编码读,不然报错
with open('b.txt',mode='wb') as f:
    msg='你好啊,派大星'
    f.write(msg.encode('gbk'))     #编码格式为 ’GBK‘

🐬正确读取
with open('b.txt',mode='rb') as f:
    l=f.read()
    print(type(l))                 #<class 'bytes'>
    print(l.decode('gbk'))         #解码格式为 ’GBK‘

🐬错误读取
with open('b.txt',mode='rb') as f:
    l=f.read()
    print(type(l))
    print(l.decode('utf-8'))       #解码不对应,报错!!

2、a b 模式

with open('b.txt',mode='ab') as f:
    f.write('你好'.encode('utf-8'))
posted @ 2020-11-28 15:43  给你骨质唱疏松  阅读(381)  评论(0编辑  收藏  举报