34

我正在为 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 的结果?

4

1 回答 1

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

在这里,files是 a 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)
... 
>>> 
于 2017-02-15T10:38:18.813 回答