[Tutor] walking directories

Alan Gauld alan.gauld at freenet.co.uk
Sat Jan 8 01:05:41 CET 2005


> I have many python scripts in various directories of 
> varying depth under my home directory, and I need to 
> change one line in each of these files.

personally I'd use find and sed in Linux, right tool 
for the job etc...

But if you really must wheel out a howitzer to shoot 
a squirrel...

> I thought about using os.walk with os.path.join eg
> 
> >>> for r,d,f in os.walk('.'):
> ...     print os.path.join(r,d,f)

Shouldn't that be os.path.walk()?

And os.path.walk takes 3 arguments:
the starting point
a function that it calls
a placeholder for arguments to the function

A simple file printer is:

>>> def f(arg, dir, names): print names
>>> os.path.walk('.', f, None)

In your case you want to write an f() that iterates 
over the names argument and opens each file, does 
a string replacement and closs the file again.

You probably should do some validation on the name 
and file type too...

Thats why I'd use find and sed...

Alan G.



More information about the Tutor mailing list