循环结果来自Path.glob()(Pathlib)

时间:2017-02-15 10:31:54

标签: python 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的结果?

1 个答案:

答案 0 :(得分:13)

>>> from pathlib import Path
>>> 
>>> dir = Path.cwd()
>>> 
>>> files = dir.glob('*.txt')
>>> 
>>> type(files)
<class 'generator'>

此处,filesgenerator,只能读取一次然后用尽。所以,当你第二次尝试阅读它时,你就不会拥有它。

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