问题描述
当我尝试遍历两个目录时,第一个目录的文件数量较少,第二个目录的文件数量较大,我遇到了一个问题:我想对大量文件使用iglob,但这是行不通的。
large_n_files = glob.iglob(pathtodir)
small_n_files = glob.iglob(pathtootherdir)
for s in small_n_files:
for l in large_n_files:
print(l,s)
产量(假设例如small_n = 2,large_n = 3)
l1 s1
l2 s1
l3 s1
当我切换到针对large_n_files的glob
,我得到了想要的结果,即
large_n_files = glob.glob(pathtodir)
small_n_files = glob.iglob(pathtootherdir)
for s in small_n_files:
for l in large_n_files:
print(l,s)
产量
l1 s1
l2 s1
l3 s1
l1 s2
l2 s2
l3 s2
为什么会这样呢? (我想我必须学习更多关于迭代器的信息。。。)如果我想对大量文件使用它,会不会效率下降? 我该如何解决?
1楼
当您这样做时:
small_n_files = glob.iglob(pathtootherdir)
您回到迭代器; 这意味着您只能迭代一次。
另一方面,当您执行以下操作时:
large_n_files = glob.glob(pathtodir)
然后您创建一个列表,可以重复多次。 (它为small_n_files的每个循环创建一个迭代器对象)。 但您的内存中有完整列表。
如果您不想将large_n_files保留在内存中(因为它很大),则可以使用以下代码:
small_n_files = glob.iglob(pathtootherdir)
for s in small_n_files:
for l in glob.iglob(pathtodir):
print(l,s)
这样,您就永远不会在内存中包含pathtodir的完整列表。