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

时间:2019-07-12 13:10:18

标签: python file exception

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

2 个答案:

答案 0 :(得分:2)

这是一个可行的示例,如果找不到该文件,则会抛出该文件,并抛出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")

如果文件不存在,您仍然会得到FileNotFoundErorr

示例:

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

答案 1 :(得分:0)

使用exception handling:-

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