The listdir() function of os module in Python

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:

# 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:

['AntAndGrasshopper.txt', 'BaaBaa.txt', 'RowYourBoat.txt', 'Copy of BaaBaa.txt', 'Rain.txt', 'Wheels.txt', 'OneTwoBuckle.txt']
<class 'list'>

 


Copyright 2024 © pythontic.com