tags:

views:

28

answers:

1

I have a python script that is trying to create a directory tree dynamically depending on the user input. This is what my code looks like so far.

if make_directories:
   os.makedirs(outer_dir)
   os.chdir(outer_dir)
   for car in cars:
       os.makedirs(car)
       os.chdir(car)
       #create a bunch of text files and do other stuff, 
       os.chdir('../')
   os.chdir('../')

I was wondering if there was a better way to do this? I don't know if this is bad convention to keep changing directories like this.

Note: Cars is a list of car names that the user provides, outer_dir is a directory name that is also provided by the user

A: 

I tend to do path manipulations rather than changing directories; just because the current directory is a bit of "implied state" whereas the paths can be explicity rooted.

if make_directories:
    for car in cars:
        carpath = os.path.join(outer_dir, car)
        os.makedirs(carpath)
        for fn in textfiles:
            filepath = os.path.join(carpath, fn)
            #... use filepath ...
Joe Koberg
Ok this may be because of bad design, but lets say the files that are created for each dir are created in functions, some of which call more functions that create more text files. The initial functions are called where I put the comment in the code. Also, the directories are only made if make_directories is True. Would it then be easier to just use chdir()? That way I don't have to pass the make_directories boolean along with the directory's name to all of the functions?
timo tellasi
If you call functions that create files in the current directory, I guess you need to `chdir`. But I would do it in the loop, and use a root ('/' or 'c:\\', whatever) at the front of `outdir_dir`, to avoid havind to chdir back up. (thus not relying on implicit state)
Joe Koberg
Actually I found your way better. I just passed in absolute paths for filenames.
timo tellasi