python 遍历两个目录时的 glob 和 iglob
python glob and iglob when iterating over two directories
当我尝试遍历两个目录时,第一个目录的文件数量较少,第二个目录的文件数量较多,我 运行 遇到了问题:
我想对大量文件使用 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
为什么会这样? (我想我必须学习更多关于迭代器的知识......)如果我想将它用于大量文件,那么 glob 的效率会不会降低?我该如何解决这个问题?
当你这样做时:
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 的完整列表。
当我尝试遍历两个目录时,第一个目录的文件数量较少,第二个目录的文件数量较多,我 运行 遇到了问题: 我想对大量文件使用 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
为什么会这样? (我想我必须学习更多关于迭代器的知识......)如果我想将它用于大量文件,那么 glob 的效率会不会降低?我该如何解决这个问题?
当你这样做时:
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 的完整列表。