[Tutor] try and file existence

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Aug 15 15:14:31 CEST 2015


On 15/08/2015 04:39, Steven D'Aprano wrote:
> On Fri, Aug 14, 2015 at 06:28:09PM -0700, Clayton Kirkwood wrote:
>> try:
>>      fp = open( user_preferences )
>> except( PermissionError ):
>> else:
>>      with open(user_preferences ) as f:
>
>
> try:
>      fp = open(user_preferences)
> except (IOError, OSError) as e:
>      handle_error()
> else:
>      with fp as f:
>          handle_file()

I'll just point out that you can catch finer grained errors owing to 
https://www.python.org/dev/peps/pep-3151/.  There is a handy little 
table here 
https://docs.python.org/3/library/exceptions.html#exception-hierarchy

-- 
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