在python2中
with open(file, ‘wb‘) as tempf:
tempf.write(data)
with open(file, ‘w‘) as tempf:
tempf.write(data)
都是可以的,因为string无法区别是字节还是字符串。
而在python3中则要使用:
with open(file, ‘wb‘) as tempf:
tempf.write(data.encode(encoding=‘utf8‘,errors=‘ignore‘))
或
with open(file, ‘w‘) as tempf:
tempf.write(data)
因为前者写入的是bytes而后者是string。
5.读数据文件:
惯用法:
在python2中
with open(file, ‘rb‘) as tempf:
tempf.read()
和
with open(file, ‘r‘) as tempf:
tempf.read()
均可,因为前者返回一些字节,但是用的是string作容器。而后者返回的还是string。
而在python3中则要用:
with open(file, ‘rb‘) as tempf:
tempf.read().decode(encoding=‘utf8‘,errors=‘ignore‘)
或
with open(file, ‘r‘) as tempf:
tempf.read()
因为打开的模式不同,前者返回了bytes,后者返回的是string(在内部尝试bytes尝试用源文件encoding解码)。