Question

I need to modify some files using a python script, and I figure OS walk is the way to go about it. I need to modify everything under

/foo/bar
/foo/baz
/foo/bat
....for example

I've never used os.walk before, I read a bit about it and I see that it traverses down the file structure top to bottom. However, when I did a bit of debugging, the object os.walk returns is something called a generator, and I'm not sure how to go about modifying the files with this object. Does anyone know how to modify files in a top to bottom order using pythons os.walk? Examples, links to examples?

Was it helpful?

Solution

This example does what you ask (using /tmp, not /foo):

import os
for top in ['/tmp/bar', '/tmp/baz', '/tmp/bat']:
    for dirpath, dirs, files in os.walk(top):
        for filename in files:
            with open(os.path.join(dirpath, filename), 'a') as fp:
                fp.write("Kilroy\n")

Ref: http://docs.python.org/2/library/os#os.walk

OTHER TIPS

import os
for root, dirs, files in os.walk('.'):
    print root, dirs,files

you can walk the tree top-down, and collect file names/paths in a list for processing:

import os

dir = '/home/foo/Desktop'

def get_paths(dir):
    paths = []
    for root, dirs, files in os.walk(dir):
        for file in files:
            paths.append(os.path.join(root, file))
    return paths

print get_paths(dir)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top