Convert UTF16LE file to UTF8 in Python?

2020-08-05 09:54发布

问题:

I have big file with utf16le (BOM) encoding.
Is it possible to convert it to usual UTF8 by python?

Something like

file_old = open('old.txt', mode='r', encoding='utf-16-le')
file_new = open('new.txt', mode='w', encoding='utf-8')

text = file_old.read()

file_new.write(text.encode('utf-8'))

http://docs.python.org/release/2.3/lib/node126.html (-- utf_16_le UTF-16LE)

Not working. Can't understand "TypeError: must be str, not bytes" error.
python 3

回答1:

You should not be encoding it. Let the stdlib do its job.

file_new.write(text)