I was wondering whether the python library has a function that returns a file's character encoding by looking for the presence of a BOM.
I've already implemented something, but I'm just afraid I might be reinventing the wheel
Update: (based on John Machin's correction):
import codecs
def _get_encoding_from_bom(fd):
first_bytes = fd.read(4)
fd.seek(0)
bom_to_encoding = (
(codecs.BOM_UTF32_LE, 'utf-32'),
(codecs.BOM_UTF32_BE, 'utf-32'),
(codecs.BOM_UTF8, 'utf-8-sig'),
(codecs.BOM_UTF16_LE, 'utf-16'),
(codecs.BOM_UTF16_BE, 'utf-16'),
)
for bom, encoding in bom_to_encoding:
if first_bytes.startswith(bom):
return encoding
return None