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

后端 未结 5 1541
不思量自难忘°
不思量自难忘° 2020-12-23 15:57

I want to read a .csv file in python.

  • I don\'t know if the file exists.
  • My current solution is below. It feels sloppy to me because the two separate ex
5条回答
  •  旧巷少年郎
    2020-12-23 16:17

    fname = 'filenotfound.txt'
    try:
        f = open(fname, 'rb')
    except FileNotFoundError:
        print("file {} does not exist".format(fname))
    
    file filenotfound.txt does not exist
    

    exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

    https://docs.python.org/3/library/exceptions.html
    This exception does not exist in Python 2.

提交回复
热议问题