Python: How do I read and parse a unicode utf-8 text file?

元气小坏坏 提交于 2019-12-14 01:23:54

问题


I am exporting UTF-8 text from Excel and I want to read and parse the incoming data using Python. I've read all the online info so I've already tried this, for example:

 txtFile = codecs.open( 'halout.txt', 'r', 'utf-8' )
 for line in txtFile:
  print repr( line )

The error I am getting is:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte

Looking at the text file in a Hex editor, the first values are FFFE I've also tried:

txtFile.seek( 2 )

right after the 'open' but that just causes a different error.


回答1:


That is a BOM

EDIT, from the coments, it seems to be a utf-16 bom

codecs.open('foo.txt', 'r', 'utf-16')

should work.




回答2:


That file is not UTF-8; it's UTF-16LE with a byte-order marker.




回答3:


Expanding on Johnathan's comment, this code should read the file correctly:

import codecs
txtFile = codecs.open( 'halout.txt', 'r', 'utf-16' )
for line in txtFile:
   print repr( line )



回答4:


Try to see if the excel file has some blank rows (and then has values again), that might cause the unexpected error.



来源:https://stackoverflow.com/questions/1862963/python-how-do-i-read-and-parse-a-unicode-utf-8-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!