[Tutor] try and file existence

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Aug 15 04:18:16 CEST 2015

On 15/08/2015 02:28, Clayton Kirkwood wrote:
> try:
>      fp = open( user_preferences )
> except( PermissionError ):

You need a pass statement here if you don't intend doing anything with 
the error, but see my comments at the bottom.

> else:
>      with open(user_preferences ) as f:
> I originally only had the bottom open statement. Ran but file didn't exist,
> and my run failed with file doesn't exist. I figured I'd check to see if the
> file existed. This is one of those situations where a search of
> documentation for fd_exist (which I thought I'd seen once), or exist turns
> up either nothing or nothing relevant. I finally found that the try: clause
> with the open statement might help and I copied the snippet to my code. I am
> getting an indentation error: expected an indent block. What is wrong, and
> what is the best way to find out if a file exists?
> TIA,
> Clayton

There's nothing to stop you using multiple except statements with one 
try.  So something like this is how I'd go about it.

     with open(user_preferences) as f:
except PermissionError:
except FileNotFoundError:

Seee this for an explanation of exception handling 
https://docs.python.org/3/tutorial/errors.html#handling-exceptions.  A 
full list of the exceptions you'd need to consider is here 

My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

More information about the Tutor mailing list