我使用os.scandir
获取文件夹中的文件列表:
img_list2 = os.scandir('/home/shared/test')
我想得到第一个元素。
我正在尝试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'
所以我试过了:
>>> 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'>
>>>
所以就像在列表中我们可以得到第一个元素值,我们可以从os.scandir
得到它吗?
答案 0 :(得分:2)
os.scandir()
返回包含给定路径的目录条目的迭代器,请参阅help(os.scandir)
:
scandir(...)
scandir(path='.') -> iterator of DirEntry objects for given path
要从中获取值,请调用其上的内置next
:
next(img_list2)
这将从迭代器返回值,直到它耗尽(并且StopIteration
被引发)。
您还可以将其包装在list
调用中,该调用会在所有条目中创建list
并使其成为可索引的,但如果您只需要第一个过分的元素。
iterator.next()
Python 3.0
起,{p> iterator.__next__()
被移除; dunder next()
方法将其替换为调用它的内置GRANT CREATE SESSION TO USER;
。
答案 1 :(得分:1)
next()
将为您提供img_list2
迭代器中的下一项:
next(img_list2)