问题描述:

How can I loop through a fixed number of files within a directory with glob.glob? If there's more than x files within that directory, I only want to loop through x and then exit the loop. How do I do this?

网友答案:

Use itertools.islice() and glob.iglob() to efficiently limit the number of results you can loop over:

from itertools import islice
import glob

x = 1000
limited_files = islice(glob.iglob('pattern.*'), x)
for filename in limited_files:
    #  handle filename

Even if there are many, way too many matches in a directory, you'll never handle more than the first 1000 matches, without creating several lists with matching filenames.

相关阅读:
Top