2012-10-05 62 views
9

我試圖導入CSV CSV文件時,使用此代碼:的UnicodeDecodeError在Python 3進口

import csv 
    import sys 

    def load_csv(filename): 
     # Open file for reading 
     file = open(filename, 'r') 

     # Read in file 
     return csv.reader(file, delimiter=',', quotechar='\n') 

    def main(argv): 
     csv_file = load_csv("myfile.csv") 

     for item in csv_file: 
      print(item) 

    if __name__ == "__main__": 
     main(sys.argv[1:]) 

這是我的csv文件的樣本:

foo,bar,test,1,2 
    this,wont,work,because,α 

和錯誤:

Traceback (most recent call last): 
     File "test.py", line 22, in <module> 
     main(sys.argv[1:]) 
     File "test.py", line 18, in main 
     for item in csv_file: 
     File "/usr/lib/python3.2/encodings/ascii.py", line 26, in decode 
     return codecs.ascii_decode(input, self.errors)[0] 
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 40: ordinal not in range(128) 

顯然,這是打在CSV末尾的字符和投擲的錯誤,但我在一個不知如何解決這個問題。任何幫助?

這就是:

Python 3.2.3 (default, Apr 23 2012, 23:35:30) 
    [GCC 4.7.0 20120414 (prerelease)] on linux2 

回答

10

看來你的問題可以歸結爲:

print("α") 

你可以通過指定PYTHONIOENCODING修復:

$ PYTHONIOENCODING=utf-8 python3 test.py > output.txt 

注:

$ python3 test.py 

應該像你一樣工作R端子配置支持的話,其中test.py

import csv 

with open('myfile.csv', newline='', encoding='utf-8') as file: 
    for row in csv.reader(file): 
     print(row) 

如果open()具有以上則沒有encoding參數,你會得到UnicodeDecodeErrorLC_ALL=C

同樣與LC_ALL=C即使沒有重定向也會得到UnicodeEncodeError,即在這種情況下需要PYTHONIOENCODING

10

python docs,你必須設置該文件的編碼。這裏是一個來自網站的例子:

import csv 

with open('some.csv', newline='', encoding='utf-8') as f: 
    reader = csv.reader(f) 
    for row in reader: 
    print(row) 

編輯:您的問題似乎與打印時發生。嘗試使用漂亮的打印機:

import csv 
import pprint 

with open('some.csv', newline='', encoding='utf-8') as f: 
    reader = csv.reader(f) 
    for row in reader: 
    pprint.pprint(row) 
+1

設置文件的編碼對解決問題沒有任何幫助...... 'file = open(filename,'r',encoding ='utf-8')'仍然給我UnicodeDecodeError:'ascii'編解碼器無法解碼位置40中的字節0xce:序號不在範圍內(128)' –

+0

啊,它與'print'無法顯示unicode字符有關。這個關於Quora的問題可能有答案 - 它使用漂亮的打印機:http://www.quora.com/How-do-you-print-a-python-unicode-data-structure – TheDude

+1

我認爲這個錯誤沒有任何根本不用打印。在print()甚至運行之前,它在for循環的開始處發生錯誤。使用pprint編輯的示例代碼會產生與以前相同的錯誤,從而進一步強化了這一說法。 我很難過。 –