我試圖導入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
設置文件的編碼對解決問題沒有任何幫助...... 'file = open(filename,'r',encoding ='utf-8')'仍然給我UnicodeDecodeError:'ascii'編解碼器無法解碼位置40中的字節0xce:序號不在範圍內(128)' –
啊,它與'print'無法顯示unicode字符有關。這個關於Quora的問題可能有答案 - 它使用漂亮的打印機:http://www.quora.com/How-do-you-print-a-python-unicode-data-structure – TheDude
我認爲這個錯誤沒有任何根本不用打印。在print()甚至運行之前,它在for循環的開始處發生錯誤。使用pprint編輯的示例代碼會產生與以前相同的錯誤,從而進一步強化了這一說法。 我很難過。 –