[Tutor] Equivalent exception of os.path.exists()

Dave Angel davea at ieee.org
Mon Nov 30 21:46:46 CET 2009

spir wrote:
> biboy mendz <bibsmendez at gmail.com> dixit:
>> http://pastebin.ca/1693849
>> This is end-of-chapter3 exercise of the book Core Python Programming.
>> I'm reading/searching in the book and other materials but is 
>> unsuccessful. There are at least 50 exceptions listed but I can't find 
>> anything close.
>> I commented out my modified script to just what *should* be applicable. 
>> Can you please point me to the right direction? TIA.
> What is your question?
> If it's about the type of exception raised when os.path.exists fails, well, sure it's hard to find:
>   print os.path.exists("foo".bar)
>   ==> False
> The output beeing a logical value, there is no failure.
> A general method to get a type of exception matching a particuliar kind of error is to provoke an error of this given kind, eg:
>   f = file("foo.bar")
>   ==>
> Traceback (most recent call last):
>   File "__essai__.py", line 10, in <module>
>     f = file("foo.bar")
> IOError: [Errno 2] No such file or directory: 'foo.bar'
> In this case, the type is IOError.
> Denis
> ________________________________
> la vita e estrany
> http://spir.wikidot.com/
As others have pointed out, you need to spell out the question you're 
trying to answer.  Not all of us have a copy of that book, or have it 
handy in any case.

If you're trying to write a function that produces equivalent results to 
os.path.exists(), but uses exceptions to do so, you'll need to know 
first what that function does.  It checks if a path is valid, and refers 
to an existing file *or* *directory*.    So if you decide that the path 
doesn't specify a file, then you also have to check if it specifies a 

It's not actually correct to just use open(), even for the file portion, 
because open() may fail if the file is already open exclusively by 
another program.  For a little while, the file exists, but you may not 
open it.

I think if I couldn't use any of the os.path functions, I'd resort to 
using os.walk().  Once again, I wouldn't expect any exceptions.  I'd 
just walk through the whole tree, and see if the desired file was on any 
of the returned lists.  Don't forget to use case-insensitive comparison 
on Windows.

The problem with a poorly reworded question is there are answers that 
are perhaps useless to the original problem.  If I couldn't use 
os.path.exists(), then I'd substitute os.path.isfile() and 
os.path.isdir(), checking the one if the other fails.  But this wouldn't 
raise any exceptions either, so it wouldn't be the learning experience 
the author wants.

My suspicion is that the author just wants you to try to do an open() 
(readonly), inside a try/except block, and to successfully handle the 
exception.  Among other things, this requires you to find out which 
exception type to use.


More information about the Tutor mailing list