A little disappointed so far

Graham Nicholls graham at rockcons.co.uk
Sun May 18 21:17:39 EDT 2003


Aahz wrote:

> In article <PRVxa.118$573.48 at news-binary.blueyonder.co.uk>,
> Graham Nicholls  <graham at rockcons.co.uk> wrote:
>>
>>Is there an equivalent of [ -f $filename ] to test for the existence of
>>filename in Python?  Things like this seem essential for a shell tool
>>language.
> 
> Sure:
> 
> os.path.isfile(filename)
Aha, thanks.  
> 
> But Alex will probably trundle by in a moment to tell you that in many
> cases, you don't want to do that.  Python's powerful exception handling
> system means that most of the time you just do:
> 
> try:
>     f = file(filename)
> except IOError:
>     <handle exception>
> 
I guess thats reasonably succinct.

> Thing is, no matter how much you test, there's always the possibility of
> a race condition that prevents you from opening a file.  I'll note that
> since you're mostly doing shell script equivalents, it's more likely
> that you'll want to do the tests (because you want to know whether
> something is a file or a directory).

I suppose so, unless you've some sort of temporary file creation function.
So, generally is it the "Python Way" to try things and handle the
exceptions, as in try... except, or to run os.path.isfile ? 
Are there good reasons for this? I'm not a computer scientist, and I am
beginning to suspect that Python is a CS language.  Is that unfair?  (That
implies that being a CS language is a bad thing, which I'm not at all sure
of :-)
> 
> One of the great things about the Python docs is that once you know
> about os and os.path, you know where to look for information.

Tell me more, please - I'm confused by that statement.  Do you mean that I
should have run dir (IIRC) on the os module? 

BTW, my i=i+1 bug - how do you avoid these, or are they common?
-- 
Graham Nicholls
All round good guy.




More information about the Python-list mailing list