2

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

1 Answer 1

2

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 ...
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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)
Actually I found your way better. I just passed in absolute paths for filenames.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.