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

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

提交回复
热议问题