Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #93021

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

References <8B8C6022-75BE-41FC-9B18-7D89AD34A35A@gmail.com> <E2B820B1-2238-4914-BD20-02AAF60F3243@gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2015-06-22 16:48 -0600
Subject Re: Simplest/Idiomatic way to count files in a directory (using pathlib)
Newsgroups comp.lang.python
Message-ID <mailman.714.1435013345.13271.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Jun 22, 2015 at 4:33 PM, Travis Griggs <travisgriggs@gmail.com> wrote:
> <I should proof my posts before I send them, sorry>
>
> 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())
>
> didn’t work.

len doesn't work on iterators for a number of reasons:

* It would exhaust the iterator, preventing further use.
* The iterator is not necessarily finite.
* Even if it's finite, the length is not necessarily deterministic.
Consider this simple generator:

def gen():
    while random.randrange(2):
        yield 42

> I don’t see anything 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())

This is the usual idiom for counting the number of items yielded from
an iterator. Alternatively you can use len(list(self.path.iterdir()))
if you don't mind constructing a list of the entire directory listing.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Simplest/Idiomatic way to count files in a directory (using pathlib) Ian Kelly <ian.g.kelly@gmail.com> - 2015-06-22 16:48 -0600

csiph-web