Since Python 3.5, you can use os.scandir
.
The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file
to know if it's a file or not, and that saves CPU time because stat
is already done when scanning dir in Windows:
example to list a directory and print files bigger than max_value
bytes:
for dentry in os.scandir("/path/to/dir"):
if dentry.stat().st_size > max_value:
print("{} is biiiig".format(dentry.name))
(read an extensive performance-based answer of mine here)