by-passing exception [Q]

Tim Peters tim_one at email.msn.com
Sun Apr 11 03:24:52 EDT 1999


[Bruno Mattarollo]
> 	Perhaps this is a stupid question, but it's saturday and
> it's almost 2AM, so you may understand my state-of-mind :-)

It's after 3AM now, so you may understand mine <wink>.

> 	I have a script that has to check a directory for the
> existence of a file, so I do a os.stat(path-to-file) ... But I want
> to continue processing even if this file doesn't exist, so I tryed
> this:
>
> 	try:
> 		os.stat(path-to-file)
> 	except IOError, msg:
> 		blah blah ....
>
> 	But I get an exception ... and it doesn't go into the
> except statement...

If you had written up a complete problem report, showing the traceback, the
answer would have bit you in the nose:

>>> import os
>>> os.stat("nothing")
Traceback (innermost last):
  File "<stdin>", line 1, in ?
OSError: [Errno 2] No such file or directory: 'nothing'
>>>

That is, it raises OSError, not IOError.  So try that:

>>> try:
...     os.stat("nothing")
... except OSError, detail:
...     print "oops!", detail
...
oops! [Errno 2] No such file or directory: 'nothing'
>>>

> Should I be doing a os.listdir(path-to-dir-where-file-resides)
> and checking there?

>>> dir(os.path)
['__builtins__', '__doc__', '__file__', '__name__', 'abspath', 'basename',
 'commonprefix', 'dirname', 'exists', 'expanduser', 'expandvars',
'getatime',
 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount',
 'join', 'normcase', 'normpath', 'os', 'split', 'splitdrive', 'splitext',
 'splitunc', 'stat', 'string', 'varchars', 'walk']
>>> # ponder, ponder, ...
>>> print os.path.exists.__doc__
Test whether a path exists
>>> os.path.exists("nothing")
0
>>>

> I am a little bit confused ... Perhaps it's time to go to
> bed or to stop drinking beer while working ... :-)

Let's not go to extremes.  Interactive mode is a programmer's best friend,
especially when tired and drunk at 2AM!

just-try-getting-a-dog-to-tell-you-whether-a-file-exists-ly y'rs  - tim






More information about the Python-list mailing list