我正在努力处理 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)
...
>>>