作者pkyosx (Insomnia)
看板Python
标题Re: [问题] 请问一下unicode的问题
时间Sat Jan 6 03:46:01 2007
因为读 utf-8 的档案一直出错 最後一气之下实验了一些东西
错误讯息:
>>> file("d:\\utf8.txt","r").read().decode('utf8').encode('big5')
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0:
unexpected code byte
首先.. 在 windows 的环境下 如果你是存 unicode 事实上就是存成 utf-16
其次 在python编辑器上如果没改的话预设是用 big5
再来 utf-16 utf-8 在 档案的最前端都会有 0xFEFF 我猜是 header
实验一:
我在 notepad 档案里面放一个字 "我" 然後各存成 utf-8, unicode(utf-16)
读档案并decode
>>> file("d:\\unicode.txt","r").read().decode('utf-16')
u'\u6211'
>>> file("d:\\utf8.txt","r").read().decode('utf8')
u'\ufeff\u6211'
干点一: utf-8 decode 出来以後 多个 0xFEFF
实验二: 删除 python 读 utf-8 出错的可能性
>>> file("d:\\unicode.txt","w").write('我'.decode('big5').encode('utf-16'))
>>> file("d:\\utf8.txt","w").write('我'.decode('big5').encode('utf-8'))
>>> file("d:\\unicode.txt","r").read().decode('utf-16')
u'\u6211'
>>> file("d:\\utf8.txt","r").read().decode('utf8')
u'\u6211'
以防万一 把档案复制一份到其他资料夹在读看看
>>> file("d:\\wow\\utf8.txt","r").read().decode('utf8')
u'\u6211'
>>> file("d:\\wow\\unicode.txt","r").read().decode('utf-16')
u'\u6211'
奇怪 一切都正常!!
接着我用 notepad 把两个档案打开 只做存档 不更改内容
>>> file("d:\\unicode.txt","r").read().decode('utf-16')
u'\u6211'
>>> file("d:\\utf8.txt","r").read().decode('utf8')
u'\ufeff\u6211'
干点二: 用 notepad 存过的 0xFEFF 又回来了
直接用 Ultra Editor Hex进位模式验证:
存档前:
=> FF FE 11 62
存档後: 终於发现问题就在於 notepad 存 UTF-8 的时候多存东西上去了!!
=> FF FE FF FE 11 62
但是 notepad 存 unicode(UTF-16), Ultra-Editor 存 UTF-8, UTF-16 都不会有问题
=> FF FE 11 62
结论:
习惯用 notepad 开文件的人小心阿= =" ...TMD
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.113.128.52
1F:推 buganini:那就是BOM啊,用来识别编码的 01/06 06:22