【问题标题】:Loop over results from Path.glob() (Pathlib) [duplicate]循环来自 Path.glob() (Pathlib)的结果[重复]
【发布时间】:2017-07-03 23:06:25
【问题描述】:

我正在为 Python 3.6 中 Pathlib 模块的 Path.glob() 方法的结果而苦苦挣扎。

from pathlib import Path

dir = Path.cwd()

files = dir.glob('*.txt')
print(list(files))
>> [WindowsPath('C:/whatever/file1.txt'), WindowsPath('C:/whatever/file2.txt')]

for file in files:
    print(file)
    print('Check.')
>>

显然,glob 找到了文件,但没有执行 for 循环。如何循环遍历 pathlib-glob-search 的结果?

【问题讨论】:

  • 迭代器在list(files) 被消耗,你必须再次执行files = dir.glob('*.txt')

标签: python glob pathlib


【解决方案1】:
>>> from pathlib import Path
>>> 
>>> dir = Path.cwd()
>>> 
>>> files = dir.glob('*.txt')
>>> 
>>> type(files)
<class 'generator'>

这里,files 是一个generator,它只能读取一次,然后用尽。因此,当您尝试第二次阅读它时,您将不会拥有它。

>>> for i in files:
...     print(i)
... 
/home/ahsanul/test/hello1.txt
/home/ahsanul/test/hello2.txt
/home/ahsanul/test/hello3.txt
/home/ahsanul/test/b.txt
>>> # let's loop though for the 2nd time
... 
>>> for i in files:
...     print(i)
... 
>>> 

【讨论】:

  • 我明白了,谢谢。我不知道发电机会“耗尽”或“消耗”。我将深入研究它以了解更多信息。但是,我的代码现在可以工作了。感谢您的帮助(也感谢摩西)!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多