Getting the Directory/Path details

Peter Otten __peter__ at web.de
Fri Sep 26 06:24:41 EDT 2003


Kali K E wrote:

> Thank you very much for the answer. It works fine when used first
> time. But when the directory already exists I am getting the following
> traceback message.
> Traceback (most recent call last):
>   File "temp6.py", line 15, in ?
>     os.makedirs(os.path.join(folder, sf))
>   File "/usr/lib/python2.2/os.py", line 203, in makedirs
>     mkdir(name, mode)
> OSError: [Errno 17] File exists:
> '/hda1/home/kalike/chnages/python/result'
> 
> How do I take care in such a case?

I modified the code to accept already existing directories. The strategy is:
Try to create the directory
If creation fails, see if the directory already exists.
If yes move to the next directory, otherwise throw an exception.

class DirectoryException(Exception): pass

for sf in subfolders:
    dirpath = os.path.join(folder, sf)
    try:
        os.makedirs(dirpath)
    except OSError, e:
        if e.errno == 17:
            if not os.path.isdir(dirpath):
                raise DirectoryException, "'%s' can neither be created nor
is it an existing directory" % dirpath
        else:
            raise # cannot handle it here


> Also can you please let me know where I can search for all these OS or
> system calls. Is it available as a document some where?

It seems you are not familiar with the concept of Exceptions. So, if you
were already exposed to another programming language, I'd suggest reading
the tutorial that comes with your distribution first, otherwise look out
for a textbook.

The relevant links on the python site are (in recommended reading order):

http://www.python.org/doc/current/tut/tut.html
http://www.python.org/doc/current/lib/module-os.path.html
http://www.python.org/doc/current/lib/module-os.html

Peter





More information about the Python-list mailing list