克隆github存储库并将它们导入文件会引发解码错误

时间:2018-01-27 16:24:42

标签: python git character-encoding dataset

我有一个python脚本,我克隆github存储库,然后我打开具有.py扩展名的文件并将它们全部放入另一个文件中,所以我有一个包含所有python脚本的大文件。

languages = ['py', 'c']

    for lang in languages:
    files = glob.glob(filename + '/**/*.' + lang, recursive=True)
    outfile = open(filename + '/' + lang + '.data', 'w')

    print('processing {} {} files'.format(len(files), lang))

    for infile in files:
        with open(infile) as datafile:
            for line in datafile:
                line = line.rstrip()
                if line:
                    outfile.write(line + '\n')

抛出的错误是:

in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 7227: 
character maps to <undefined>.

可能是由于文件使用不同的标准编码。 有没有解决的办法 ? 我的最终目标是拥有一个包含所有克隆.py文件的大型python文件,以及包含所有克隆c文件的.c文件。 那么我可以避免使用不同的编码方法吗?或者有不同的方法吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用codecs.open打开文件时指定编码:

import codecs

outfile = codecs.open(filename + '/' + lang + '.data', 'w', encoding='utf8')

with codecs.open(infile, encoding='utf8') as datafile:

P.S。您可能希望阅读有关处理Unicode的文章:https://docs.python.org/2/howto/unicode.html

P.P.S。当您使用Python 3时,you may just add an encoding argument to your existing open function没有导入编解码器模块:

outfile = open(filename + '/' + lang + '.data', 'w', encoding='utf8')

with open(infile, encoding='utf8') as datafile:

答案 1 :(得分:0)

该文件可能包含一些不正确的utf8数据。您应该检查它们具有哪种编码。一旦文件连接起来就很难恢复它。

否则,尝试将参数error='surrogateescape'添加到打开的调用中,用于读取和写入。这应该保留输入的字节值,即使它不是正确的utf8。