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


Groups > comp.lang.python > #93019 > unrolled thread

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

Started byTravis Griggs <travisgriggs@gmail.com>
First post2015-06-22 15:31 -0700
Last post2015-06-23 12:17 -0400
Articles 3 — 3 participants

Back to article view | Back to comp.lang.python


Contents

  Simplest/Idiomatic way to count files in a directory (using pathlib) Travis Griggs <travisgriggs@gmail.com> - 2015-06-22 15:31 -0700
    Re: Simplest/Idiomatic way to count files in a directory (using pathlib) Paul Rubin <no.email@nospam.invalid> - 2015-06-22 18:32 -0700
      Re: Simplest/Idiomatic way to count files in a directory (using pathlib) Terry Reedy <tjreedy@udel.edu> - 2015-06-23 12:17 -0400

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

FromTravis Griggs <travisgriggs@gmail.com>
Date2015-06-22 15:31 -0700
SubjectSimplest/Idiomatic way to count files in a directory (using pathlib)
Message-ID<mailman.712.1435012328.13271.python-list@python.org>
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())

[toc] | [next] | [standalone]


#93025

FromPaul Rubin <no.email@nospam.invalid>
Date2015-06-22 18:32 -0700
Message-ID<87k2uvjjjv.fsf@nightsong.com>
In reply to#93019
Travis Griggs <travisgriggs@gmail.com> writes:
> The following seems to obtuse/clever for its own good:
>     return sum(1 for _ in self.path.iterdir())

I've generally done something like that.  I suppose it could be added to
itertools.

[toc] | [prev] | [next] | [standalone]


#93041

FromTerry Reedy <tjreedy@udel.edu>
Date2015-06-23 12:17 -0400
Message-ID<mailman.731.1435076289.13271.python-list@python.org>
In reply to#93025
On 6/22/2015 9:32 PM, Paul Rubin wrote:
> Travis Griggs <travisgriggs@gmail.com> writes:
>> The following seems to obtuse/clever for its own good:
>>      return sum(1 for _ in self.path.iterdir())

I disagree.  For one who understands counting and Python, this is a 
direct way to define the count of a finite iterable.  A functionalist 
would prefer it to the obvious 3-line version with a for statement.

> I've generally done something like that.  I suppose it could be added to
> itertools.

itertools callables all produce iterators.  The above only consumes an 
iterable.

-- 
Terry Jan Reedy

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web