Search code examples
pythonpathgeneratorpathlib

pathlib path.glob iterating results with for loop question


from pathlib import Path, PureWindowsPath

path=Path(PureWindowsPath('c:/test'))
print(file for file in path.glob('*.*'))
print("\n")
for file in path.glob('*.*'):print(file)

I am a noob learning python, i cannot understand the difference between both for loops and result. I get generator object in one and file names in the other.

result is:

<generator object <genexpr> at 0x000002D8446B3970>


c:\test\Changes.xlsx
c:\test\North Accounts V1.1.xlsx
c:\test\North Customer Contact Details.xlsx
c:\test\Py_Test.xlsx

Process finished with exit code 0


Solution

  • path.glob is an iterable and your expression file for file in path.glob(..) makes an iterable out of an iterable. This is unnecessary but also gives the wrong result since when you print it you get the string representation of the iterable (which is this weird number) and not of the elements it iterates over.