path module / class

chris.atlee at gmail.com chris.atlee at gmail.com
Fri Nov 18 14:08:34 EST 2005


Hi Neil,

Neil Hodgson wrote:
[snip]
>     There is no PEP yet but there is a wiki page.
> http://wiki.python.org/moin/PathClass
>     Guido was unenthusiastic so a good step would be to produce some
> compelling examples.

I guess it depends on what is "compelling" :)

I've been trying to come up with some cases that I've run into where
the path module has helped.  One case I just came across was trying to
do the equivalent of 'du -s *' in python, i.e. get the size of each of
a directory's subdirectories.  My two implemenations are below:

import os
import os.path
from path import path

def du_std(d):
    """Return a mapping of subdirectory name to total size of files in
        that subdirectory, much like 'du -s *' does.

       This implementation uses only the current python standard
       libraries"""
    retval = {}
    # Why is os.listdir() and not os.path.listdir()?
    # Yet another point of confusion
    for subdir in os.listdir(d):
        subdir = os.path.join(d, subdir)
        if os.path.isdir(subdir):
            s = 0
            for root, dirs, files in os.walk(subdir):
                s += sum(os.path.getsize(os.path.join(root,f)) for f in
files)
            retval[subdir] = s
    return retval

def du_path(d):
    """Return a mapping of subdirectory name to total size of files in
       that subdirectory, much like 'du -s *' does.

       This implementation uses the proposed path module"""
    retval = {}
    for subdir in path(d).dirs():
        retval[subdir] = sum(f.getsize() for f in subdir.walkfiles())
    return retval

I find the second easier to read, and easier to write - I got caught
writing the first one when I wrote os.path.listdir() instead of
os.listdir().

Cheers,
Chris




More information about the Python-list mailing list