2011-04-13 55 views
1

我试图运行一些代码来简单地浏览一堆文件,并将那些碰巧是.txt文件的文件写入同一个文件,删除所有空格。下面是一些简单的代码是应该做的伎俩:Python - Python 3.1似乎无法处理UTF-16编码文件?

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() 

但是,相反,我得到以下错误:

文件“/usr/lib/python3.1/codecs.py”,线300,在解码 (结果,消耗)= self._buffer_decode(数据,self.errors,最终) UnicodeDecodeError错误: 'UTF8' 编解码器不能在位置0解码字节0xFE的:意外的代码字节

原来这些.txt文件全部采用UTF-16格式(无论如何,都依据FireFox)。我以为Python 3.x应该能够处理任何类型的字符编码?

最佳, 乔治娜

+1

的建议,你可以告诉Python的这些文件是UTF-16? – Gabe 2011-04-13 05:35:11

+0

我该怎么做? – Georgina 2011-04-13 05:37:04

+0

OK,oneliner:'output_file.write(input_file.read()。decode('utf-16')。replace(u“”,u“”)。encode('desired encoding'))' – janislaw 2011-04-13 10:38:54

回答

6

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

+0

Woops - thanks !就像你发布这个,iI发现了这个伟大的帖子:http://stackoverflow.com/questions/3140010/converting-from-utf-16-to-utf-8-in-python-3 – Georgina 2011-04-13 05:42:19

+0

完美的答案。谢谢。 – 2013-10-24 00:58:15

3

有各种utf-16编码。

  • UTF-16是大端没有BOM

  • UTF-16乐小端没有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' 

您可以使用这些编码通过@filmor's answer