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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章