os.walk: Get entire path
xtian
wilberforce at gmail.com
Sun Aug 29 11:49:36 EDT 2004
Florian Lindner wrote:
> Hello,
> when I'm walking through a file system hierarchy using os.walk, how
can I
> get the full path of a file or dir? normpath and abspath don't work.
> Thx,
> Florian
os.walk() is a generator that yields (current directory,
subdirectories, files), and subdirectories and files are lists of
relative names.
(See http://docs.python.org/lib/os-file-dir.html#l2h-1474)
To get the full path of a file or subdirectory while doing a walk, you
can join the name to the current directory (using os.path.join()), and
then use os.path.abspath() on the lot to get the full path (if current
directory is already absolute you don't need that last step).
>>> for d, subs, files in os.walk("."):
print os.path.abspath(os.path.join(d, subs[0]))
break
C:\Python23\BACKUP
On a general note, if you're not sure what something does or the exact
format something is returned in, try playing around with it at the
interactive prompt. If you do:
>>> for item in os.walk("."):
print item
break
...it's pretty easy to see what's going on.
Cheers,
xtian
More information about the Python-list
mailing list