Recursive directory scripting

Will Stuyvesant hwlgw at
Sun Oct 13 00:08:53 CEST 2002

Often I have to do something in the current directory and
recursively below.  Like cleaning up.  Can I use python
for this?  Yes I can, the scripts are below.  I tried to
make it portable so it would also work with linux, but I
gave up.  Maybe you can?

Improvements and other comments are welcome!

----------------  walkcommand.bat  --------------
python C:\bin\ %1 %2 %3 %4 %5 %6 %7 %8 %9
----------------  end of walkcommand.bat  -------

----------------  ---------------
import os, sys, string

def callback(arg, directory, files):    # files unused
    olddir = os.getcwd()

def program_params():
    return string.join(sys.argv[1:], ' ')

if len(sys.argv) < 2:
    info = ('I will execute your command recursively '+
         'from the current directory\n'+
         'Your command: ')
    cmdline = raw_input(info)
    cmdline = program_params() 

os.path.walk(".", callback, cmdline)
----------------  end of  --------

With 'C:\bin' added to my %PATH% and walkcommand.bat and there I can now clean my directory and any
directories below like this: 
C:\doc> walkcommand del *.aux *.toc *.log *.*~ *~ *.bak

Of course it is saver to put 'del *.aux *.toc *.log *.*~
*~ *.bak' in a file called clean.bat in C:\bin and do:
C:\doc> walkcommand clean

That saves you from accidentally typing *.* <wink>

Copying a file to all subdirectories goes like this:
C:\doc> walkcommand copy C:\doc\myfiletocopy

Programmers used to batch environments may find it hard to
live without giant listings; we would find it hard to use
                -- D.M. Ritchie

More information about the Python-list mailing list