Getting all the *files* from a directory -- A better way??
kens at sightreader.com
Wed Mar 28 02:45:31 CEST 2001
----- Original Message -----
From: "Paul Jackson" <pj at sgi.com>
To: <python-list at python.org>
Sent: Tuesday, March 27, 2001 3:15 PM
Subject: Re: Getting all the *files* from a directory -- A better way??
> 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).
Actually '/' is generally portable. I use os.path.join for combining
variables, but I use '/' within hard-coded relative paths.
f = os.path.join(root, 'doc/chapter2/spam.html')
f = os.path.join(root, os.path.join('doc', os.path.join('chapter2',
This is fine because open() and all other file functions automagically
normalize the path to the operating system. Warning: if you want
to use the result in a command line (e.g. os.popen()) be sure to
normalize the path with os.path.normpath().
> 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