尝试在python中读取文件时处理异常的好方法是什么? [英] What is a good way to handle exceptions when trying to read a file in python?

查看:212
本文介绍了尝试在python中读取文件时处理异常的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中读取.csv文件。

I want to read a .csv file in python.


  • 我不知道文件是否存在。

  • 我当前的解决方案如下。我觉得草率,因为两个单独的异常测试并列在一起。

是否有更漂亮的方法?

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


推荐答案

我想我误解了所要求的内容。重新阅读,看来蒂姆的答案就是你想要的。但是,让我添加一下:如果要从 open 捕获异常,则必须包装 open 尝试中。如果对 open 的调用位于 with 的标题中,则 with 必须进行尝试才能捕获异常。

I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that.

所以答案是:提姆的方式还是不,你做得正确。

So the answer is either: "Tim's way" or "No, you're doing it correctly.".

先前所有评论所引用的无益答案:

Previous unhelpful answer to which all the comments refer:

import os

if os.path.exists(fName):
   with open(fName, 'rb') as f:
       try:
           # do stuff
       except : # whatever reader errors you care about
           # handle error

这篇关于尝试在python中读取文件时处理异常的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆