Recursive directory scripting

Drew Perttula drewp at bigasterisk.com
Sun Oct 13 05:35:19 EDT 2002


hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:<cb035744.0210121408.43fd18fb at posting.google.com>...
> 
> Improvements and other comments are welcome!

> 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

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

I love os.path.walk as much as the next programmer (who's writing
an application that needs to know the directory tree), but as a unix
shell user, I find this walkcommand.py as weird as a python program 
that just copies the contents from one file to another. Shells, zsh in
particular (www.zsh.org), let you do all sorts of file selection tricks.
Globbing through subdirs, for example, is totally natural.

rm **/*.aux **/*.toc **/*.log **/*~ **/*.bak
# there are surely other variants (this one was the most obvious to me).
# ** means any number of subdirs

for x (**/*(/)) { cp myfiletocopy $x }
# (/) restricts to just dirs

The latter formation could be easily turned into a 'walkcommand' function
that could be used the same way as yours. I haven't bothered, since the
loop list changes all the time, for me. For example, your walkcommand can't
quite do this:

for x (**/*.png) { convert $x $x:r.jpg }
# converts all png in all subdirs to jpeg files.
# the :r operator strips the extension of a filename (leaving the 'r'oot)




Bonus commands that involve subdirectories:

What python C modules support simultaneous threads?

  grep -l ALLOW_THREADS Python-2.2/**/*.c

Are there more lines (approx) of C or python in the python distribution?

  wc -l Python-2.2/**/*.c | tail -1
  wc -l Python-2.2/**/*.py | tail -1



More information about the Python-list mailing list