简体   繁体   English

遍历目录中固定数量的文件

[英]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 ? 如何使用glob.glob在目录中循环访问固定数量的文件? If there's more than x files within that directory, I only want to loop through x and then exit the loop. 如果该目录中的文件超过x个,我只想遍历x个然后退出循环。 How do I do this? 我该怎么做呢?

Use itertools.islice() and glob.iglob() to efficiently limit the number of results you can loop over: 使用itertools.islice()glob.iglob()有效限制可以循环遍历的结果数:

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. 即使目录中有太多匹配项,如果不创建多个具有匹配文件名的列表,您将永远无法处理前1000个匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM