129 of 151 menu

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 DirEntry of module os,
    which contains iterable files and subfolders
  • method getcwd module os,
    which returns the current working directory
  • method makedirs of module os,
    which creates a directory
  • method rmtree of module shutil,
    which recursively deletes a folder
  • method copytree of module shutil,
    which recursively copies a folder
  • method path.join of module os,
    which unites the paths
byenru