The listdir() function of os module in Python

The listdir() function of os module in Python returns the name of the entries present in a directory.

Os Updated 6 May 2023 1 min read

Overview

  • The listdir() function returns a list of names of the entries present in a directory. Examples of entries include files, directories, links and others.
  • The returned list of names does not include "." and ".." which represent the current directory and the parent directory.

Example

python
# Example Python program that lists the names of

            # the entries present in a directory

            import os

# File path

            path     = "./songs"

# Retrieve the names of entries in a directory

            names     = os.listdir(path)

# Print the entries

            print(names)

            print(type(names))

Output

Output
['AntAndGrasshopper.txt', 'BaaBaa.txt', 'RowYourBoat.txt', 'Copy of BaaBaa.txt', 'Rain.txt', 'Wheels.txt', 'OneTwoBuckle.txt']

            <class 'list'>