[Tutor] select particular directories and files
Peter Otten
__peter__ at web.de
Tue Aug 30 08:45:02 CEST 2011
questions anon wrote:
> I am trying to select particular files within a particular subdirectory, I
> have been able to do both but not together!
> When I try to select my files within the dir loop nothing comes up, but
> when I leave the files outside the dir loops it selects all the files
> not just the ones in the dirs I have selected.
> The code I am using is:
>
> import os
>
> MainFolder=r"D:/samples/"
>
> for (path, dirs, files) in os.walk(MainFolder):
> for dir in dirs:
dirs contains the names of subdirectories of the directory you are currently
processing, but you are interested in the parent directory which you get
with with os.path.basename(path)
> if dir=='01':
> print "selected directories are:",dir
>
> for ncfile in dir:
> if ncfile[-3:]=='.nc':
> print "ncfiles are:", ncfile
>
> Any feedback will be greatly appreciated!!
import os
mainfolder = "d:/samples"
foldername = "01"
fileext = ".nc"
for path, folders, files in os.walk(mainfolder):
if os.path.basename(path) == foldername:
for file in files:
if file.endswith(fileext):
print os.path.join(path, file)
More information about the Tutor
mailing list