44

I'm struggling with the result of the Path.glob() method of the Pathlib module in Python 3.6.

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

Evidently, glob found files, but the for-loop is not executed. How can I loop over the results of a pathlib-glob-search?

keyx
  • 567
  • 1
  • 4
  • 5

1 Answers1

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

Here, files is a generator, which can be read only once and then get exhausted. So, when you will try to read it second time, you won't have it.

>>> 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)
... 
>>> 
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • I got it, thanks. I was unaware that generators get "exhausted" or "consumed". I'll dig deeper into it to understand more. However, my code works now. Thanks for your help (also thanks to Moses)! – keyx Feb 15 '17 at 13:37
  • Just FYI, `dir` is a builtin function, so is best avoided as a variable name – Bede Constantinides Nov 08 '22 at 00:48