Recursive directory scripting
Will Stuyvesant
hwlgw at hotmail.com
Sat Oct 12 18:08:53 EDT 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\walkcommand.py %1 %2 %3 %4 %5 %6 %7 %8 %9
---------------- end of walkcommand.bat -------
---------------- walkcommand.py ---------------
import os, sys, string
def callback(arg, directory, files): # files unused
olddir = os.getcwd()
os.chdir(directory)
os.system(arg)
os.chdir(olddir)
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)
else:
cmdline = program_params()
os.path.walk(".", callback, cmdline)
---------------- end of walkcommand.py --------
With 'C:\bin' added to my %PATH% and walkcommand.bat and
walkcommand.py 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
them.
-- D.M. Ritchie
'''
More information about the Python-list
mailing list