The scandir method of the os module
The scandir method iterates over files and subfolders that are in a folder. In the method parameter, we set the path to the folder. The method returns the os.DirEntry object.
Syntax
import os
os.scandir(path to directory)
Example
Let's find out the structure of our directory:
import os
print(os.scandir('dir'))
As a result of executing the code, we will receive the object os.DirEntry:
<nt.ScandirIterator object at 0x000001478707FF00>
Example
Now let's iterate over the resulting object using a loop. In order to free up system resources, after the loop is complete, it is necessary to close the iteration using the scandir method:
import os
for file in os.scandir('dir'):
print(file)
os.scandir('dir').close()
The result of the executed code:
<DirEntry 'dir1'>
<DirEntry 'file1.txt'>
<DirEntry 'file2.txt'>
Example
We can also output only the file names by applying the name attribute to the resulting object:
import os
for file in os.scandir('dir'):
print(file.name)
os.scandir('dir').close()
The result of the executed code:
dir1
file1.txt
file2.txt
See also
-
object
DirEntryof moduleos,
which contains iterable files and subfolders -
method
getcwdmoduleos,
which returns the current working directory -
method
makedirsof moduleos,
which creates a directory -
method
rmtreeof moduleshutil,
which recursively deletes a folder -
method
copytreeof moduleshutil,
which recursively copies a folder -
method
path.joinof moduleos,
which unites the paths