Python學習過程遇到的Bug-不斷更新


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 csv def 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 are
typically NOT created by text editors. They are created e.g. by "save as
csv" from a spreadsheet program, or as an output option by some database
query 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 be
capable of reproducing the original field division. Here for example is
a dump of a little file I just created using Excel 2003:
...
This sentence in the documentation is NOT an error: """If csvfile is a
file object, it must be opened with the ‘b’ flag on platforms where that
makes a difference."""
 

   雖然這個解釋沒有告訴我們怎么解決這個問題,但是我根據上面這段話,將代碼改成下面這樣就OK了:

import csv def 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:
       # ...

 

...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM