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

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

提交回复
热议问题