[Tutor] select particular directories and files

questions anon questions.anon at gmail.com
Wed Aug 31 01:21:06 CEST 2011


Thanks, that also works really well.
One of the hardest things I am finding with programming is that there is
always more than one way to do something. This is a good and bad thing. Bad
for beginners!!
thanks

On Tue, Aug 30, 2011 at 4:45 PM, Peter Otten <__peter__ at web.de> wrote:

> 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)
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110831/7d1be414/attachment.html>


More information about the Tutor mailing list