0

The snippets does not execute the for loop after the file_counts = len(list(images)). If I drop this line, the loop is working fine. I wonder what happened. Is there anyone who can help me to explain and fix it?

    from pathlib import Path

    print(Path.cwd())

    path = Path.cwd()
    images = path.glob('*.jpg')
    file_counts = len(list(images))

    for image in images:
        print(f" file is {images} ")
passion
  • 387
  • 4
  • 16

1 Answers1

2

Fix:

Instead of converting glob result to list while computing the len. You should store the result as the list itself and then compute the length.

images = list(path.glob('*.jpg'))
file_counts = len(images)

Details:

Since, path.glob doesn't return, but yields all matching file,

images = path.glob('*.jpg')

The images variable you have created is not a typical container(list) which you can iterate, again and again, it is instead a generator

Even though generators behave like an iterator, they are exhausted after a single-use. i.e. you cannot iterate them more than once.

So when you do list(images) your images generator is used up for converting it into the list. Which then you are using to get the length.

file_counts = len(list(images))
Anurag Wagh
  • 1,086
  • 6
  • 16
  • Thank you for your kind answer. It worked. I thought that the result from the path.glob('.jpg') can be stored in the variable and then list it. It is not working that way. Logically it makes sense. For the for-loop, I just add the line for the demonstration. I knew it is the generator. Thank you again for your kind help. – passion Jun 10 '20 at 04:37
  • can you post stack trace of the error you are getting? – Anurag Wagh Jun 10 '20 at 06:18