Getting all the *files* from a directory -- A better way??
pj at sgi.com
Wed Mar 28 01:15:51 CEST 2001
Quentin Crain asks:
|> Here is how I get all the files from a directory:
|> files=filter(os.path.isfile,["%s/%s"%(dir,f) for f in os.listdir
|> Is this *REALLY* the Pythonic way to do this? (OR, why does
|> os.listdir return only file names, and not the path given
Close - better to use os.path.join (more portable across
operating environments with different path component
separator characters, such as '\' in DOS/Windows).
files = filter(
[os.path.join(dir, f) for f in os.listdir(dir)]
I'd say that the os.listdir() method only returns the
directory entries (by simple basename), not with any
path prefixed, because it is intended to be basic
operation on a directory, and directories have just
the simple name entries, not full pathnames, in them.
What one wants to do with those directory entries, after
extracting them with os.listdir(), can vary all over the
lot, and may or may not involve joining the directory path.
So that should be left up to the caller of listdir().
I won't rest till it's the best ...
Manager, Linux System Software
Paul Jackson <pj at sgi.com> 1.650.933.1373
More information about the Python-list