views:

229

answers:

4

Hello

Does anybody know how to get the encoding of a file in Python. I know that you can use the codecs module to open a file with a specific encoding but you have to know it in advance.

import codecs
f = codecs.open("file.txt", "r", "utf-8")

Is there a way to detect automatically which encoding is used for a file?

Thanks in advance

Edit: Thanks everybody for very interesting answsers. You may also be interested by http://whatismyencoding.com/ which is based on chardet (more over the site is powered by bottle python framework)

+5  A: 

Mark Pilgrim's Universal Encoding Detector.

jleedev
+5  A: 

You may use BOM (http://en.wikipedia.org/wiki/Byte_order_mark) to detect the encoding, or try this library http://chardet.feedparser.org/.

ZelluX
+6  A: 

Unfortunately there is no 'correct' way to determine the encoding of a file by looking at the file itself. This is a universal problem, not limited to python or any particular file system.

If you're reading an XML file, the first line in the file might give you a hint of what the encoding is.

Otherwise, you will have to use some heuristics-based approach like chardet (one of the solutions given in other answers) which tries to guess the encoding by examining the data in the file in raw byte format. If you're on Windows, I believe the Windows API also exposes methods to try and guess the encoding based on the data in the file.

HS
+2  A: 

There is Unicode Dammit from Beautiful Soup, which uses chardet but adds a couple of extra features.

It tries to read the encoding from inside XML or HTML files. Then it tries looking for a BOM or something like that at the start of the file. If it can't do that, it makes use of chardet.

Craig McQueen