我在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的结果?
答案 0 :(得分:13)
>>> 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)
...
>>>