当python中不存在输入文件时,如何处理异常?

当python中不存在输入文件时,如何处理异常?,python,file,exception,Python,File,Exception,假设我有一个名为“student.csv”的文件。但在我的python中,我错误地将“student1.csv”作为文件输入传递,该文件不存在。如何处理此异常以进一步停止执行。下面是一个工作示例,如果找不到该文件,它将抛出和FileNotFoundError异常 try: f = open('student.csv') except FileNotFoundError: print('File does not exist') finally: f.close()

假设我有一个名为“student.csv”的文件。但在我的python中,我错误地将“student1.csv”作为文件输入传递,该文件不存在。如何处理此异常以进一步停止执行。

下面是一个工作示例,如果找不到该文件,它将抛出和
FileNotFoundError
异常

try:
    f = open('student.csv')
except FileNotFoundError:
    print('File does not exist')
finally:
    f.close()
    print("File Closed")
另一种方式:

try:
    with open("student.csv") as f:
        print("I will do some Magic with this")
except FileNotFoundError:
    print('File does not exist')
此外,如果您不想自定义错误消息,您可以使用

with open("student.csv") as f:
       print("I will do some Magic with this")
如果文件不存在,您仍将获得一个
filenotfounderor

例如:

FileNotFoundError: [Errno 2] No such file or directory: 'student1.csv'

使用异常处理
:-

try:
    file = open('student.csv')
except Exception as e:
    print('File not found. Check the name of file.')

让程序崩溃并出现FileNotFoundError似乎是处理异常的一种非常好的方法。完全按照需要停止程序的执行;任何阅读堆栈跟踪的人都确切地知道问题所在。请使用try-except-block@Kevin:Sure的可能重复项,因为没有什么比看到堆栈跟踪更能培养最终用户的信心了。@ScottHunter不认为这是用户敌对的设计;可以将其视为鼓励用户学习编程的基础知识。必须诊断未捕获的异常会构建角色;-)建议:f.在finally块中关闭()?更好的方法是:将open('student.csv')作为f:
,文件将在with块后关闭,而无需添加
close()