Catching a specific IO error
John Machin
sjmachin at lexicon.net
Tue Apr 24 21:09:22 EDT 2007
On 25/04/2007 4:06 AM, Steven Howe wrote:
> Steve Holden wrote:
>> Thomas Krüger wrote:
>>
>>> Tina I schrieb:
>>>
>>>> Now, this works but of course it catches every IOError, and I can not
>>>> figure out how to restrict it to only catch the "[Errno 2]"?
>>>>
>>> There's an example that uses the error number:
>>> http://docs.python.org/tut/node10.html#SECTION0010300000000000000000
>>>
>>>
>> So what you'll need to do is catch all IOError exceptions, then test
>> to see if you've got (one of) the particular one(s) you are interested
>> in. If not then you can re-raise the same error with a bare "raise"
>> statement, and any containing exception handlers will be triggered. If
>> there are none then you will see the familiar traceback termination
>> message.
>>
>> regards
>> Steve
>>
> you could also use some pre-testing of the filename os.path.isfile,
> os.path.isdir, os.path.split are good
> functions to test file/directory existence.
In general, this is laborious, tedious, and possibly even platform
dependent. Then you still need to wrap the open call in try/accept. Why
bother?
In particular, (1) please explain how os.path.split helps with existence
testing:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
| >>> import os.path
| >>> os.path.split(r'no\such\path\nothing.nix')
('no\\such\\path', 'nothing.nix')
(2) please explain why you avoided mentioning os.path.exists.
More information about the Python-list
mailing list