Simplest/Idiomatic way to count files in a directory (using pathlib)

Peter Otten __peter__ at web.de
Tue Jun 23 08:02:09 EDT 2015


Travis Griggs wrote:

> Subject nearly says it all.
> 
> If i’m using pathlib, what’s the simplest/idiomatic way to simply count
> how many files are in a given directory?
> 
> I was surprised (at first) when
> 
>     len(self.path.iterdir())
> 
> I don’t say anything on the in the .stat() object that helps me.
> 
> I could of course do the 4 liner:
> 
>     count = 0
>     for _ in self.path.iterdir():
>         count += 1
>     return count
> 
> The following seems to obtuse/clever for its own good:
> 
>     return sum(1 for _ in self.path.iterdir())

Put the "cleverness" into its own function

def iterlen(items):
    return sum(1 for _ items)

num_files = iterlen(path.iterdir())

With the proper unit tests in place you may even switch to more exotic 
approaches later:

def iterlen(items):
    """Exhaust an iterator an return the number of items.

    Does not check for a __len__() method.

    >>> iterlen(())
    0
    >>> iterlen([42])
    1
    >>> iterlen("abc")
    3

    >>> class A:
    ...     def __len__(self): return 42
    ...     def __iter__(self): yield from "abc"
    >>> a = A()
    >>> len(a)
    42
    >>> iterlen(a)
    3
    """
    d = collections.deque(enumerate(items, 1), maxlen=1)
    return d.pop()[0] if d else 0





More information about the Python-list mailing list