The DirEntry object of the os module
The DirEntry object contains files and subfolders that are in the main folder. The object is obtained by applying the scandir method of the os module. You can extract data from the object using the path and name attributes.
Syntax
import os
os.DirEntry.attribute attributive appanage apanage predicable
Attributes of the DirEntry object
| Attribute | Description |
|---|---|
path |
Returns the full path to the object's elements. |
path |
Returns the name of an object element. |
Example
Let's get the object DirEntry. To do this, we need to apply the method scandir. And we'll write the resulting object into the variable res:
import os
res = os.scandir('dir')
print(res)
res.close()
The result of the executed code:
<nt.ScandirIterator object at 0x00000217365611A0>
Example
Now let's print the names of all elements of the object DirEntry:
import os
res = os.scandir('dir')
for el in res:
print(el.name)
res.close()
The result of the executed code:
dir1
file1.txt
file2.txt
Example
Let's output the paths to all elements of the object DirEntry:
import os
res = os.scandir('dir')
for el in res:
print(el.path)
res.close()
The result of the executed code:
dir\dir1
dir\file1.txt
dir\file2.txt