Python3 pathlib 一行,用于检查 Path 是否至少有一个特定扩展名的文件

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

我的第一次尝试产生了这个结果:

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

我认为这是低效的,因为整个生成器对象(.glob() returns)在继续之前必须被列表理解消耗掉。

我的第二次尝试是在生成器上手动调用 .__next__() 并手动捕获 StopIteration,但我不认为可以在一行中完成:

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

总的来说,我是一个 Python 菜鸟,我想知道是否可以使用单线解决方案(至少比我第一次尝试的效率更高)。

使用any():

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

或者更简单地说,

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