recursive file editing

Michael Geary Mike at DeleteThis.Geary.com
Mon Apr 5 13:18:48 EDT 2004


> for filetuple in os.walk('foo'):
> ...     for filename in filetuple[2]:
> ...         fileopen = file(filename, 'r+')
>             fileopen.write("This works !")
>             fileopen.close()
>
> which seems a bit of a clumsy way to do it.

You have the right idea, although this would be a bit cleaner:

for root, dirs, files in os.walk( 'foo' ):
    for name in files:
        etc...

You might want to take a look at the documentation for os.walk. It explains
all this and has a couple of good code samples.

> And besides it only works if I run python from directory foo,
> otherwise it tells me "no such file or directory".

You mean if you run Python from the *parent* directory of foo, right?

'foo' is a relative path, not an absolute one, so it gets appended to the
current directory.

-Mike





More information about the Python-list mailing list