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

后端 未结 5 1536
不思量自难忘°
不思量自难忘° 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.

    0 讨论(0)
  • 2020-12-23 16:20

    Here is a read/write example. The with statements insure the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm

    import sys
    
    fIn = 'symbolsIn.csv'
    fOut = 'symbolsOut.csv'
    
    try:
       with open(fIn, 'r') as f:
          file_content = f.read()
          print "read file " + fIn
       if not file_content:
          print "no data in file " + fIn
          file_content = "name,phone,address\n"
       with open(fOut, 'w') as dest:
          dest.write(file_content)
          print "wrote file " + fOut
    except IOError as e:
       print "I/O error({0}): {1}".format(e.errno, e.strerror)
    except: #handle other exceptions such as attribute errors
       print "Unexpected error:", sys.exc_info()[0]
    print "done"
    
    0 讨论(0)
  • 2020-12-23 16:24

    Adding to @Josh's example;

    fName = [FILE TO OPEN]
    if os.path.exists(fName):
        with open(fName, 'rb') as f:
            #add you code to handle the file contents here.
    elif IOError:
        print "Unable to open file: "+str(fName)
    

    This way you can attempt to open the file, but if it doesn't exist (if it raises an IOError), alert the user!

    0 讨论(0)
  • 2020-12-23 16:34

    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
    

    0 讨论(0)
  • 2020-12-23 16:36

    How about this:

    try:
        f = open(fname, 'rb')
    except OSError:
        print "Could not open/read file:", fname
        sys.exit()
    
    with f:
        reader = csv.reader(f)
        for row in reader:
            pass #do stuff here
    
    0 讨论(0)
提交回复
热议问题