is there a better way to walk a file system?
gsakkis at rutgers.edu
Fri Jul 1 18:49:08 CEST 2005
"Peter Hansen" wrote:
> ina wrote:
> > I want to walk a folder structor and group all the files by extention.
> > Here is the code I put together is there a better way of doing this?
> > <code>
> If you were to download Jason Orendorff's "path" module, which is a
> convenient single-file package that vastly simplifies all manner of
> dealings with directory and file names, I suspect your example code
> could be reduced to less than half the number of lines it now uses, and
> with a corresponding increase in readability and maintainability.
Well, it's exactly half non-blank lines (10) and still readable; of
course it can be compressed more but we're not doing perl here <wink>.
from path import path
from itertools import groupby
root = len(sys.argv) > 1 and sys.argv or '.'
for ext,iterFiles in groupby(sorted(path(root).walkfiles(),
print "%s: %d files" % (ext, len(tuple(iterFiles)))
By the way, from this example I discovered that properties cannot be
unbound, i.e. using path.ext instead of getExtension raises TypeError.
Couldn't/shouldn't Class.prop(instance) be allowed as equivalent of
instance.prop, just as methods ?
> The answer to the question "is there a better way of doing this?" in
> relation to paths is always "yes, use Jason Orendorff's path module".
More information about the Python-list