/tmp/ python3
Python 3.2.3 (default, Feb 20 2013, 14:44:27)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1 = open("unicode.txt", 'r').read()
>>> print(f1)
你好
>>> f2 = open("unicode.txt", 'rb').read() #二进制方式打开
>>> print(f2)
b'\xe5\xaf\x92\xe5\x86\xb7\n'
>>> f2.decode()
'你好\n'
>>> f1.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
python 3中只有unicode str,所以把decode方法去掉了。python3环境中,f1已经是unicode str了,不用decode。
如果文件内容不是unicode编码的,要先以二进制方式打开,读入比特流,再解码。