Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 849
keyx Avatar asked Feb 15 '17 10:02

keyx


People also ask

What does Pathlib path return?

parts : returns a tuple that provides access to the path's components. name : the path component without any directory. parent : sequence providing access to the logical ancestors of the path. stem : final path component without its suffix.

What does Pathlib path do?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.

Is Pathlib path PathLike?

pathlib. Path (WindowsPath, PosixPath, etc.) objects are not considered PathLike : PY-30747.

What does import Pathlib do in Python?

Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python's standard utility modules. Path classes in Pathlib module are divided into pure paths and concrete paths.


1 Answers

>>> 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)
... 
>>> 
like image 55
Ahsanul Haque Avatar answered Oct 11 '22 01:10

Ahsanul Haque