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

spir denis.spir at free.fr
Mon Nov 30 22:25:33 CET 2009


biboy mendz <bibsmendez at gmail.com> dixit:

> 
> 
> spir wrote:
> >
> > 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
> >
> >   
> My question is: i'm looking for type of exception that more or less 
> equivalent to os.path.exists attribute. I know for a fact that this 
> method yields true or false. The exercise in the book says use 
> try-except in place of os.path.exists(). That sure is (to me) quite 
> difficult task. Instead of using the available function you're are 
> tasked to do the alternative.
> 
> Lie and Tim's input are true that raw_input doesnt do anything or you 
> cant catch exception error from it. And i'm wrong in placing the 
> try-except clause, it should be on the fobj-open line. But im still 
> looking for the exception that will be raised when i input a filename 
> and that file already exists. I hope you get what i mean :-)

Right. So, the exercise is about replacing an explicit check by try...except. But unlike what you seem to think above, you won't get any error from file *writing*.
Think at variables: python does not make any distinction between creation or change, so that you you won't get any error by "writing" a variable that already exist, even if your intention was to create a new one (and you wrote a wrong name). Because there is no syntactic difference between creation and change. Conversely, if you create a new variable when you intended to change an existing one, you won't get any nice error, it will be silently processed. Right?
The same with files. So you cannot have such errors at file writing, if the file exists, it will be overwritten. So, you can only use try...except for file *reading*.
See my previous post.


(*) Except in the case when you try to overwrite you don't have (as user) the right to change, or if you try to create a file in a folder you don't have writing right in.

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



More information about the Tutor mailing list