[Tutor] select particular directories and files

Emile van Sebille emile at fenx.com
Tue Aug 30 02:07:22 CEST 2011


On 8/29/2011 4:52 PM questions anon said...
> I am trying to select particular files within
> a particular subdirectory,

You might find glob a better starting point:

ActivePython 2.6.6.15 (ActiveState Software Inc.) based on
Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import glob
 >>> help(glob.glob)
Help on function glob in module glob:

glob(pathname)
     Return a list of paths matching a pathname pattern.

     The pattern may contain simple shell-style wildcards a la fnmatch.

 >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\*.txt'):
     print filename
...
C:\WSG\GL\2011-08\2011-01-WIP-Details.txt
C:\WSG\GL\2011-08\2011-02-WIP-Details.txt
C:\WSG\GL\2011-08\2011-03-WIP-Details.txt
C:\WSG\GL\2011-08\2011-04-WIP-Details.txt
C:\WSG\GL\2011-08\2011-05-WIP-Details.txt
C:\WSG\GL\2011-08\2011-06-WIP-Details.txt
C:\WSG\GL\2011-08\2011-07 - bankToRec.txt
C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt
C:\WSG\GL\2011-08\2011-07-WIP-Details.txt
C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt
C:\WSG\GL\2011-08\BankRecUtils.txt
C:\WSG\GL\2011-08\CapitalizationExamples.txt
C:\WSG\GL\2011-08\DEALLOCATE-2011-04.txt
C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt
C:\WSG\GL\2011-08\MAR DEALLOCATION.txt
C:\WSG\GL\2011-08\Notes.txt
C:\WSG\GL\2011-08\shipping safety net util.txt
C:\WSG\GL\2011-08\UNBILLED WIP.txt
C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt
C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt
C:\WSG\GL\2011-08\vacation accrual notes.txt
 >>>




> 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:
>          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!!
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list