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

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

提交回复
热议问题