Python Script for Running a Python Program over Different Files inthe Directory

Terry Reedy tjreedy at udel.edu
Sat Mar 13 09:10:41 EST 2004


"Shalen chhabra" <shalen_itbhu at hotmail.com> wrote in message
news:Law10-F11d3qix8xR5f00010c98 at hotmail.com...
> Hey,
>
> Can anyone give me a snippet for running a python program over all the
files
> in the directory.
> For ex:  I have ten files in a directory and I want to run a python
program
> against all of these files, I wish to do the same using another python
code
> instead of running each of these files one by one, which would be
cumbersome
> giving the argv of each file every single time.
>
> This can be easily done using a shell script but I just wanted to have a
> flavour of python for this.

I would consider following strategy:

def process_file(fileobject): <do whatever to file>

if __name__ == '__main__':
  from sys import argv
  if argv is file, open, and call process_file
  if directory, use os.path to get list and iterate over

You could also process multiple arguments to process subset of all files.
You can also use os.walk (or os.path.walk) to iterate recursively into
subdirectories.

By separating process_file as a function from conditional 'what file to
process' logic, you can also import and use function in another program.

Terry J. Reedy







More information about the Python-list mailing list