Getting all the *files* from a directory -- A better way??
Paul Jackson
pj at sgi.com
Tue Mar 27 18:15:51 EST 2001
Quentin Crain asks:
|> Here is how I get all the files from a directory:
|>
|> dir="a/b/c"
|> files=filter(os.path.isfile,["%s/%s"%(dir,f) for f in os.listdir
|> (dir)])
|>
|> Is this *REALLY* the Pythonic way to do this? (OR, why does
|> os.listdir return only file names, and not the path given
|> prepended?)
Close - better to use os.path.join (more portable across
operating environments with different path component
separator characters, such as '\' in DOS/Windows).
Try:
dir="a/b/c"
files = filter(
os.path.isfile,
[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
mailing list