What is a good way to handle exceptions when trying to read a file in python?

問題:

I want to read a .csv file in python.我想在 python 中讀取 .csv 文件。

  • I don't know if the file exists.我不知道文件是否存在。
  • My current solution is below.我目前的解決方案如下。 It feels sloppy to me because the two separate exception tests are awkwardly juxtaposed.我覺得很草率,因爲兩個單獨的異常測試笨拙地並列在一起。

Is there a prettier way to do it?有沒有更漂亮的方法來做到這一點?

import csv    
fName = "aFile.csv"

try:
    with open(fName, 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            pass #do stuff here
    
except IOError:
    print "Could not read file:", fName

解決方案:

參考: https://stackoom.com/en/question/Nbwv
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章