2017-02-15 45 views
1

我正在使用Python 3.6中的Pathlib模塊的Path.glob()方法的結果掙扎。從Path.glob()(Pathlib)循環結果

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

顯然,水珠找到的文件,但不執行for循環。我如何循環遍歷pathlib-glob-search的結果?

+2

迭代器得到了在'名單消耗(文件)',你就必須做'文件= dir.glob( '* .txt的')'再次 –

回答

4
>>> 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) 
... 
>>> 
+0

我知道了,謝謝。我不知道發電機會「耗盡」或「消耗」。我會更深入地瞭解更多。但是,我的代碼現在可以工作。感謝您的幫助(也感謝摩西)! – keyx