detecting and creating directories

Martin von Loewis loewis at informatik.hu-berlin.de
Tue Oct 30 07:31:54 EST 2001


"Steve Holden" <sholden at holdenweb.com> writes:

> > for ten extra points, explain why this is a lousy way to
> > do this.
> 
> Because the effbot is inherently clueful, and has suggested this is not the
> best way?

Not sure what Fredrik had in mind, but considering that the original
question was

>>  I found the module that has the command to make directories, but I
>> have not been lucky finding a way  to check for the existance of a
>> directory (so it is not there, I can create it).

my approach would be

try:
    os.mkdir(path)
except OSError,(num,msg):
    if num != errno.EEXIST:
        raise

This is just a single system call, and the system atomically checks
whether the directory is there, and creates it if it is not. If you
want, you can analyse the EEXIST error in more detail (checking
whether the existing file really is a directory, whether it is really
owned by the correct user, etc.)

Regards,
Martin



More information about the Python-list mailing list