Loop over results from Path.glob() (Pathlib) [duplicate] Loop over results from Path.glob() (Pathlib) [duplicate] python python

Loop over results from Path.glob() (Pathlib) [duplicate]


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