簡體   English   中英

克隆github存儲庫並將其導入文件會引發解碼錯誤

[英]Cloning github repositories and importing them to a file throws an decoding error

我有一個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文件。 那么我可以避免使用不同的編碼方式還是有其他解決方法呢?

您可以嘗試使用codecs.open在打開文件時指定編碼:

import codecs

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

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

PS:您可能需要閱讀有關處理Unicode的這篇文章: https : //docs.python.org/2/howto/unicode.html

PPS在使用Python 3時, 您可以僅在現有的open函數中添加一個編碼參數,而無需導入編解碼器模塊:

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

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

該文件可能包含一些不正確的utf8數據。 您應該檢查它們具有哪種編碼。 文件連接后,將更難恢復它。

否則,嘗試將參數error='surrogateescape'到打開的調用中,以進行讀取和寫入。 即使它不是正確的utf8,也應保留輸入的字節值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM