recursing through files in a folder

Steve Holden steve at holdenweb.com
Fri Oct 1 09:36:18 EDT 2004


Scott Carlson wrote:

> New to Python.  Very new.
> 
> I need to pass a parameter to the program I create that points to a
> folder.  (How are params passed in?)
> 
The sys module has an argv member,  with the usual convention that the 
program name is argument zero.

So if you just add one directory (sorry, folder) name to the command 
line you need something like:

     myFolder = sys.argv[1]

> Then, I need to be able to scroll through each file in the folder,
> looking for files with a particular naming convention.
> 
> What is the best way to be able to look at each file in a folder and
> decide if I wish to use that one, and then go to the next file?
> 
The easiest way would be to use the "glob" module, specifically made for 
tricks like that. Functions in os.path can be useful to keep your code 
portable, too. Suppose you wanted a list of Windows executables in the 
folder, you'd use something like:

#!/usr/bin/python
import sys, glob, os.path

folder = sys.argv[1]
pattern = "*.exe"
filenames = glob.glob(os.path.join(folder, pattern))
for f in filenames:
     print f

and run it like so:

C:\Steve>files.py C:\Installers
C:\Installers\AdbeRdr60_enu_full.exe
C:\Installers\awrdpr210_setup.exe
    .
    .
    .
C:\Installers\winzip90.exe
C:\Installers\wxPythonWIN32-2.5.1.5-Py23.exe

or, in Unix-like environments:
$ ./files.py /c/Installers
/c/Installers/AdbeRdr60_enu_full.exe
/c/Installers/awrdpr210_setup.exe
    .
    .
    .
/c/Installers/winzip90.exe
/c/Installers/wxPythonWIN32-2.5.1.5-Py23.exe


regards
  Steve



More information about the Python-list mailing list