一, rb 二进制方式读取
f=open(‘test’,‘rb’) #b的方式不能指定编码
#‘字符串’ ———encode——字节
#字节———decode——‘字符串’
print(f.read(),decode(‘utf-8’))
f.close()
二,进行编码操作
bytes(‘玥’,encoding=‘utf-8’)
等价于:
‘玥’.encode(‘utf-8’)
三,wb 二进制方式写入
f=open(‘test’,‘wb’) #b的方式不能指定编码
f.write(bytes(‘hello\n’,encoding=‘utf-8’))
f.write(‘he\n’.encode(‘utf-8’))
注:上述两个f.write 等价
四,ab 二进制方式追加
f=open(‘test’,‘ab’)
f.write(bytes(‘llo\n’,encoding=‘utf-8’))
f.write(‘oo\n’.encode(‘utf-8’))
文件的处理方式默认以文本的方式处理,一些图片,视频等,所以无法用文本方式处理,故可以选择用b的方式处理。