1、failed to set __main__.__loader__
興奮地配置好了Python環境,運行hello.py執行個體就出現這個異常,著實讓人掃興,百度上搜了下沒有找到答案。再去Google了下,發現可能是hello.py檔案中包含非英文字元,果然將hello.py放到純英文路徑下就沒問題了。
對於eclipse下使用PyDev的情況,可以用File->Switch Workspace的方法來切換到一個英文路徑工作空間目錄
2、_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
在用下面的代碼處理csv檔案時出現這個錯誤(Python 3)
import csvdef main(): reader=csv.reader(open('userid.csv', 'rb')) for item in reader: print(item)if __name__ == '__main__': main()
經過萬能的Google搜尋,找到了問題所在:http://bugs.python.org/msg82661 ,下面是部分摘錄:
Sorry, folks, we've got an understanding problem here. CSV files aretypically NOT created by text editors. They are created e.g. by "save ascsv" from a spreadsheet program, or as an output option by some databasequery program. They can have just about any character in a field,including \r and \n. Fields containing those characters should be quoted(just like a comma) by the csv file producer. A csv reader should becapable of reproducing the original field division. Here for example isa dump of a little file I just created using Excel 2003:
...
This sentence in the documentation is NOT an error: """If csvfile is afile object, it must be opened with the ‘b’ flag on platforms where thatmakes a difference."""
雖然這個解釋沒有告訴我們怎麼解決這個問題,但是我根據上面這段話,將代碼改成下面這樣就OK了:
import csvdef main(): reader=csv.reader(open('userid.csv', 'r')) for item in reader: print(item)if __name__ == '__main__': main()
3、UnboundLocalError: local variable 'f' referenced before assignment(f.close())
代碼如下:
# Errors and Exceptions # 詳細文檔參考:http://docs.python.org/2/tutorial/errors.html try: f = codecs.open("noexistfile.txt", "rU", "utf-8") text = f.read() except Exception: sys.stderr.write('讀取檔案發生IO異常!\n') finally: f.close() sys.stderr.write('finnaly執行!\n')
這個錯誤在開啟的檔案不存在時才會發生。原因是如果檔案不存在則f是None,這時在except語句分支中執行f.close()會報一樣的錯。這與Java裡的檔案讀取異常處理不太一樣,正確的做法如下:
# Errors and Exceptions # 詳細文檔參考:http://docs.python.org/2/tutorial/errors.html try: f = codecs.open("noexistfile.txt", "rU", "utf-8") text = f.read() f.close() except Exception: sys.stderr.write('讀取檔案發生IO異常!\n') finally: sys.stderr.write('finnaly執行!\n')
其他可能的一種情況:http://blog.csdn.net/magictong/article/details/4464024
檔案讀寫的推薦寫法如下(這樣不需要顯式關閉檔案):
with open("test.txt", "r") as file_handle: for line in file_handle: # ...
...