[Tutor] directory within directory

Peter Otten __peter__ at web.de
Tue Aug 16 10:21:45 CEST 2011


questions anon wrote:

> I would like to open up a bunch of files within a folder within a folder
> and then process them and output them in another location but with the
> same folder structure. I seem to having trouble with the folder within
> folder section.
> I have a separate folder for each year and then within a year I have a
> separate folder for each month but when I try to make a directory in a new
> location it does not place the month folders within the year folders,
> instead they are all places in the outputpath together
> any help will be greatly appreciated
> 
> import os
> 
> inputpath=r'E:/temp_samples2/'
> outputpath=r'E:/figureoutputs/'
> 
> for (path, dirs, files) in os.walk(inputpath):
>     for dir in dirs:
>         print path, dir
>         newfolders=outputpath+dir

Using string concatenation to produce file paths is errorprone.
Have a look at the path manipulation functions that the os.path module has 
to offer.

>         if not os.path.exists(newfolders):
>                os.makedirs(newfolders)
>            print newfolders

dir is just the directory name. You get the source directory with

sourcepath = os.path.join(path, dir)

Now you have to remove the start of the path with

relativepath = os.path.relpath(sourcepath, inputpath)

Finally add the outputpath:

newdir = os.path.join(outputpath, relativepath)




More information about the Tutor mailing list