Python:Traceback codecs.charmap_decode(input,self.errors,decoding_table)[0]

时间:2012-08-31 10:04:57

标签: python file-io python-3.x traceback python-unicode

以下是示例代码,目的只是合并来自give文件夹及其子文件夹的文本文件。我偶尔会得到Traceback所以不知道在哪里看。还需要一些帮助来增强代码以防止空白行被合并。在合并/主文件中不显示任何行。在合并文件之前,可能需要进行一些清理或者在合并过程中忽略空行,这可能是个好主意。

文件夹中的文本文件不超过1000行,但聚合主文件可以非常容易地跨越10000多行。

import os
root = 'C:\\Dropbox\\ans7i\\'
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list]
out_file = open('C:\\Dropbox\\Python\\master.txt','w')
for path,f_name in files:
    in_file = open('%s/%s'%(path,f_name), 'r')

    # write out root/path/to/file (space) file_contents
    for line in in_file:
        out_file.write('%s/%s %s'%(path,f_name,line))
    in_file.close()

    # enter new line after each file
    out_file.write('\n')

with open('master.txt', 'r') as f:
  lines = f.readlines()
with open('master.txt', 'w') as f:
  f.write("".join(L for L in lines if L.strip())) 



Traceback (most recent call last):
  File "C:\Dropbox\Python\master.py", line 9, in <module> for line in in_file:
  File "C:\PYTHON32\LIB\encodings\cp1252.py", line  23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0]  
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 972: character maps to <undefined>  

1 个答案:

答案 0 :(得分:5)

引发错误,因为Python 3使用与内容不匹配的默认编码打开文件。

如果你所做的只是复制文件内容,最好还是使用shutil.copyfileobj() function和二进制模式打开文件。这样就可以完全避免编码问题(当然,只要你的所有源文件都是相同的编码,所以你不会得到带有混合编码的目标文件):

import shutil
import os.path

with open('C:\\Dropbox\\Python\\master.txt','wb') as output:
    for path, f_name in files:
        with open(os.path.join(path, f_name), 'rb') as input:
            shutil.copyfileobj(input, output)
        output.write(b'\n') # insert extra newline between files

我已经清理了一些代码以便使用上下文管理器(因此您的文件在完成后会自动关闭)并使用os.path为您的文件创建完整路径。

如果你确实需要逐行处理你的输入,你需要告诉Python期望的编码,所以它可以将文件内容解码为python字符串对象:

open(path, mode, encoding='UTF8')

请注意,这需要您事先知道 文件使用的编码。

如果您对python 3,文件和编码有任何疑问,请阅读Python Unicode HOWTO