Python - Python 3.1似乎无法处理UTF-16编码的文件?

Geo*_*ina 1 python utf-8 utf-16 character-encoding

我正在尝试运行一些代码来简单地浏览一堆文件并将那些碰巧是.txt文件的文件写入同一个文件中,删除所有空格.这里有一些简单的代码可以解决这个问题:

for subdir, dirs, files in os.walk(rootdir):
for file in files:
    if '.txt' in file:
        f = open(subdir+'/'+file, 'r')
        line = f.readline()
        while line:
            line2 = line.split()
            if line2:
                output_file.write(" ".join(line2)+'\n')
            line = f.readline()
        f.close()
Run Code Online (Sandbox Code Playgroud)

但相反,我收到以下错误:

文件"/usr/lib/python3.1/codecs.py",第300行,在解码中(结果,消耗)= self._buffer_decode(data,self.errors,final)UnicodeDecodeError:'utf8'编解码器无法解码字节0xfe在位置0:意外的代码字节

事实证明,这些.txt文件都是UTF-16(根据FireFox,无论如何).我以为Python 3.x应该能够处理任何类型的字符编码?

最好的,乔治娜

fil*_*mor 7

使用open(bla, 'r', encoding="utf-16").


kev*_*pie 5

有各种 utf-16 编码。

  • utf-16-be big endian 无 BOM

  • utf-16-le小端无 BOM

  • utf-16小端 + BOM

例子:

Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'a'.encode('utf-16')
>>> a
b'\xff\xfea\x00'
>>> a.decode('utf-16')
'a'
>>> a = 'a'.encode('utf-16-le')
>>> a
b'a\x00'
>>> a.decode('utf-16-le')
'a'
>>> a = 'a'.encode('utf-16-be')
>>> a
b'\x00a'
>>> a.decode('utf-16-be')
'a'
Run Code Online (Sandbox Code Playgroud)

您可以按照@filmor 的回答建议使用这些编码