Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open file using try except in python? [closed]

Tags:

python

i have a txt file i would like to use in my program named animallog1.txt. How do i open it so that it can be used in my program using try and except. I know how to use the file using open function but not using try except. Could someone tell me how it is done

like image 443
rggod Avatar asked Dec 19 '22 21:12

rggod


1 Answers

You're very vague, but I'll try and answer your question. The reason you use try and except is to catch an error. In opening a file you would get an IOError. So this is how you would open a file as such:

try:
    with open("file.txt","r") as f:
        #stuff goes here
except IOError:
    #do what you want if there is an error with the file opening
like image 109
Ryan Saxe Avatar answered Dec 31 '22 22:12

Ryan Saxe