在Python 2.x和Python 3.x中,字符串的语义发生了变化:
Python2 Python3 str bytes unicode str要求:某文本文件编码格式已知(如 UTF-8,GBK,BIG5),在Python 2.x和Python 3.x 中分别读写该文件。
Python 2.x:写入文件前对unicode编码,读入文件后对字节进行解码。
Python 3.x: open() 函数默认指定 t 以文本模式, endcoding 指定编码格式。
Python 2.x写入文件:>>> s = u'我爱Python'>>> type(s)<type 'unicode'>>>> f = open('a.txt', 'w')>>> f.write(s.encode('utf8')) #uft-8编码>>> f.flush()
# cat a.txt我爱PythonPython 2.x读取文件:
>>> f = open('a.txt', 'r')>>> txt = f.read()>>> type(txt)<type 'str'>>>> txt'\xe6\x88\x91\xe7\x88\xb1Python'>>> txt.decode('utf8') #utf-8解码u'\u6211\u7231Python'>>> print txt.decode('utf8')我爱PythonPython 3.x写入文件:
>>> s = '我爱Pyhon'>>> type(s)<class 'str'>>>> f = open('b.txt', 'w', encoding='gbk') #默认以文本模式打开,'wt'可省略为'w';默认encoding='utf8'>>> f.write(s)7>>> f.flush()Python 3.x读取文件:
>>> f = open('b.txt', 'r', encoding='gbk')>>> f.read()'我爱Pyhon'
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did126713