循环 Path.glob() (Pathlib) 的结果

Loop over results from Path.glob() (Pathlib)

我正在努力解决 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 的结果?

>>> 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)
... 
>>>