Python3 pathlib one-liner for checking if Path has at least one file of a certain extension

Viewed 135

My first try yielded this result:

if [p for p in Path().glob('*.ext')]:

Which I guess is inefficient since the entirety of the generator object (which .glob() returns) has to be consumed by the list comprehension before proceeding.

My second try was to manually call .__next__() on the generator and catch StopIteration manually, but I don't believe that can be done in one line:

try:
    Path().glob('*.ext').__next__()
except StopIteration:
    # no ".ext" files exist here
else:
    # at least one ".ext" file exists here

I'm a Python noob in general and I'm wondering if a one-liner solution is possible (at least one that's more efficient than my first attempt).

1 Answers

Use any():

if any(p for p in Path().glob('*.ext')):
   # ...

or even more simply,

if any(Path().glob('*.ext')):
   # ...
Related