Speed ain't bad

John Machin sjmachin at lexicon.net
Mon Jan 3 15:35:26 EST 2005

Anders J. Munch wrote:
> Another way is the strategy of "it's easier to ask forgiveness than
> ask permission".
> If you replace:
>     if(not os.path.isdir(zfdir)):
>         os.makedirs(zfdir)
> with:
>     try:
>         os.makedirs(zfdir)
>     except EnvironmentError:
>         pass
> then not only will your script become a micron more robust, but
> assuming zfdir typically does not exist, you will have saved the call
> to os.path.isdir.

1. Robustness: Both versions will "crash" (in the sense of an unhandled
exception) in the situation where zfdir exists but is not a directory.
The revised version just crashes later than the OP's version :-(
Trapping EnvironmentError seems not very useful -- the result will not
distinguish (on Windows 2000 at least) between the 'existing dir' and
'existing non-directory' cases.

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on
>>> import os, os.path
>>> os.path.exists('fubar_not_dir')
>>> os.path.isdir('fubar_not_dir')
>>> os.makedirs('fubar_not_dir')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "c:\Python24\lib\os.py", line 159, in makedirs
mkdir(name, mode)
OSError: [Errno 17] File exists: 'fubar_not_dir'
>>> try:
...    os.mkdir('fubar_not_dir')
... except EnvironmentError:
...    print 'trapped env err'
trapped env err
>>> os.mkdir('fubar_is_dir')
>>> os.mkdir('fubar_is_dir')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
OSError: [Errno 17] File exists: 'fubar_is_dir'

2. Efficiency: I don't see the disk I/O inefficiency in calling
os.path.isdir() before os.makedirs() -- if the relevant part of the
filesystem wasn't already in memory, the isdir() call would make it so,
and makedirs() would get a free ride, yes/no?

More information about the Python-list mailing list