[Tutor] walking directories

Jacob S. keridee at jayco.net
Sat Jan 8 03:58:15 CET 2005


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

It says in the documentation (it might be the newer ones?):

"Note: The newer os.walk() generator supplies similar functionality and can
be easier to use."
     -- 6.2 os.path -- Common pathname manipulations

And, yet, the os.walk() function states (condensed):

blah, blah, blah
Gives you three things. A root, a *list* of directories, and a *list* of
files.

The first I see wrong is he is not assuming a list return.
Secondly, it also says in the documentation:

"""
dirpath is a string, the path to the directory. dirnames is a list of the
names of the subdirectories in dirpath (excluding '.' and '..'). filenames
is a list of the names of the non-directory files in dirpath. Note that the
names in the lists contain no path components. To get a full path (which
begins with top) to a file or directory in dirpath, do os.path.join(dirpath,
name).
"""

with particular attention paid to the exclusion of "." and ".."
It would be my guess that what he enters for toplevel is interfering also
with his output.

import os

directory = "."  # Perhaps not a valid pathname?
for root, dirs, files in os.walk(directory):
    for x in files:
        print os.path.join(root,x)

yields what I believe he wants...

HTH,
Jacob Schmidt


> 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.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list