I read that scandir is an improved version of listdir, and wanted to use it to pass along a listing of possibly large directory contents in the most efficient way.
Unlike listdir, that gives the names of the files and folders directly, scandir outputs a DirEntry object generator -
from scandir import scandir
from os import listdir
path='C:/'
listdir(path) # outputs ['$Recycle.Bin', .. , 'Windows']
list(scandir(path)) # outputs [<DirEntry '$Recycle.Bin'>,.. ]
To get just the names with scandir, I currently use:
list(names.name for names in scandir(path)) #outputs ['$Recycle.Bin', .. ]
and to unpack the names in a suitable function, which is what I want, I pass along
*(names.name for names in scandir(path))
as the respective function argument, whereas with listdir I can just pass
*listdir(path)
as the argument.
Is that usage of scandir efficient? Can I perhaps somehow extract the names directly, without iterating with a for loop?