Santhosh Yedidi Santhosh Yedidi - 2 months ago 16
Python Question

Access first element in a os.scandir

I am using

os.scandir
for getting the list of files in a folder:

img_list2 = os.scandir('/home/shared/test')


I want to get the first element.

I am trying
img_list2.next()


>>> img_list2.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'posix.ScandirIterator' object has no attribute 'next'


So I tried:

>>> filt = list(img_list2)
>>> type(filt)
<class 'list'>
>>> globals()['filt']
[<DirEntry 'panaroma00010.jpg'>, <DirEntry 'panaroma00014.jpg'>, <DirEntry 'panaroma00004.jpg'>, <DirEntry 'panaroma00013.jpg'>, <DirEntry 'panaroma00007.jpg'>, <DirEntry 'panaroma00011.jpg'>, <DirEntry 'panaroma00012.jpg'>, <DirEntry 'panaroma00006.jpg'>, <DirEntry 'panaroma00009.jpg'>, <DirEntry 'panaroma00001.jpg'>, <DirEntry 'panaroma00003.jpg'>, <DirEntry 'panaroma00005.jpg'>, <DirEntry 'panaroma00002.jpg'>, <DirEntry 'panaroma00008.jpg'>]
>>> filt[1]
<DirEntry 'panaroma00014.jpg'>
>>>


So just like in list we can get the first element value, can we get it from
os.scandir
?

Jim Jim
Answer

os.scandir() returns an iterator containing the directory entries for a given path, see help(os.scandir):

scandir(...)
    scandir(path='.') -> iterator of DirEntry objects for given path

To get a value from it call the built-in next on it:

next(img_list2)

This will return values from the iterator until it is exhausted (and StopIteration is raised).

You can also wrap it in a list call which create a list out of all entries and make it indexable but if you only require the first element that is overkill.

iterator.next() was removed as of Python 3.0 with PEP 3114; a dunder iterator.__next__() method replaced it along with the built-in next() that calls it.