Skip to content Skip to sidebar Skip to footer

Typeerror: Argument Of Type 'windowspath' Is Not Iterable

The code i was trying to run is: import numpy as np import os import cv2 import matplotlib.pyplot as plt from os import listdir from pathlib import Path all_images = list(Path(r'

Solution 1:

here i was getting an index error.

glob returns a generator, not a container. You can iterate over glob's results, but you can only do that once, and you can't subscript to obtain the initial result.

If you want to use the results multiple times, or pick out the first one with [0], then use list( ... ) as your first code example showed. This will iterate over the results and store them in a list container that you can re-use or index to your heart's content.

Alternatively you could use next( ... ) to access just the initial result, but that doesn't seem to be what you want here.

EDIT

what does this WindowsPath is not iterable mean?

The list obtained from glob has several elements, and each of those elements is a Path. You can't iterate over a Path, just like you can't iterate over an int. You're certainly free to iterate over a list of Paths, or over a list of ints.

You could turn a Path into a str and iterate over that, as in the example below, but that's not what you want to do. Typically you would want to open(path, 'r') and iterate over that, which would produce lines from a text file, one line at a time.

>>>from pathlib import Path>>>>>>path = Path('foo')>>>path
PosixPath('foo')
>>>>>>for x in path:...print(x)... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'PosixPath' object is not iterable
>>>>>>for x instr(path):...print(x)... 
f
o
o
>>>

Post a Comment for "Typeerror: Argument Of Type 'windowspath' Is Not Iterable"