Reputation: 23
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
Upvotes: 2
Views: 2758
Reputation: 26769
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 ...
Upvotes: 2