当前位置: 动力学知识库 > 问答 > 编程问答 >

python - loop through fixed number of files within a directory

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: