views:

242

answers:

4

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.

+5  A: 

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

Jonathan Feinberg
Amazing psychic powers there!
fatcat1111
How do you distinguish UTF-16LE from UTF-32LE using only the first 2 bytes?
J.F. Sebastian
Good point; one can't. I've never encountered UTF-32 in a file, but I'm sure it has happened. Once. On crack.
Jonathan Feinberg
+1  A: 

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.

nosklo
From the Wikipedia page you've linked: "The UTF-8 representation of the BOM is the byte sequence EF BB BF" -- therefore the file is not in UTF-8 (due to OP sees FFFE it is a UTF-16 in little-endian order).
J.F. Sebastian
Fails: "UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte"
Mark Byers
+1  A: 

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 )
Mark Byers
A: 

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

sfa