Python3中有两种表示字符序列的类型:
str:包含Unicode字符 bytes:包含原始8位而Python2也有两种表示字符序列的类型:
str:包含原始8位 unicode:代表Unicode编码需要注意的是,Python2和Python3的Unicode和str实例都没有和特定的二进制编码相关联,因此想要把Unicode字符转换成二进制数据,必须使用encode
方法,而将二进制转换成Unicode需要使用decode
方法。
Python3中open()
函数含有encoding参数,默认值’utf-8’
import os
with open('/ex/test.bin','wb') as f:
f.write(os.urandom(10))
读取文件以rb模式读取
import os
with open('/ex/test.bin','rb') as f:
f.read()
总结
Python3中,bytes是一种包含8位的序列,str是一个包含Unicode字符的序列。
从文件读取二进制文件时,或者向其中写入二进制数据时,必须指定’wb’或者‘rb’模式。