Walking recursivly through a directory-structure
bragib at my-deja.com
bragib at my-deja.com
Mon May 29 11:55:19 EDT 2000
Hallo Paal:
You are on the right track... Just use os.path.walk(path, visit, arg)
You should write the visit function yourself. Calls the function visit
with arguments (arg, dirname, names) for each directory in the directory
tree rooted at path (including path itself, if it is a directory).
So for instance if you would had a directory tree like this
/home/bragi/tmp2/
/home/bragi/tmp2/file1.dat
/home/bragi/tmp2/file2.dat
/home/bragi/tmp2/file3.dat
/home/brag/tmp2/dir2/file1.dat
/home/bragi/tmp2/dir2/file2.dat
and you want to make a dictionary keyed by the directory name and the
dictionary values being the files in that dictionary.
import os, posixpath
dirContents = {}
def visit(arg, dirname, names):
files = []
for name in names:
if os.path.isfile(name): # keep if file
files.append(name)
dirContents[dirname] = files
arg1 = 'Hello'
arg2 = 'World'
os.path.walk('/home/bragi/tmp2', visit, (arg1, arg2))
print dirContents
Your output would be:
{'/home/bragi/tmp2': ['file2.dat', 'file3.dat', 'file1.dat'],
'/home/bragi/tmp2/dir2': ['file2.dat', 'file1.dat']}
In article <m3og5pcsvi.fsf at rancid.apocalypse.no>,
"=?iso-8859-1?q?P=E5l?= Sollie" <sollie at saint-etienne.no> wrote:
> I've been looking at os.path.walk for this, but I'm not sure how to
> implement it. Anyone able to point me in the rigth direction?
>
> --
> Pål Sollie
> sparkz at ikke.no
> sollie at bitemyshinymetalass.com
>
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list