Python os.listdir() Method

Python os.listdir() method is “used to get the list of all files and directories in the specified directory.”

Syntax

os.listdir(path)

Parameters

path: The listdir() function takes a path as a parameter, a directory that needs to be explored.

Return Value

The listdir() method returns a list containing the names of the entries in the directory given by the path.

Example 1: How to Use os.listdir() method

import os

# Open a file
path = "/Users/krunal/Desktop/code/pyt/database"
dirs = os.listdir(path)

# This would print all the files and directories
for file in dirs:
  print(file)

Output

shows.csv
Netflix.csv
marketing.csv
new_file.json
data.json
Netflix
shows.db
app.py
.vscode
purchase.csv
final.zip
sales.csv

And we get all the files in our current project directory.

Example 2: Returning the current directory

If we don’t specify any folder, the list of files and directories in the current working directory will be returned. 

import os

# Open a file

dirs = os.listdir()

# This would print all the files and directories
for file in dirs:
  print(file)

Output

shows.csv
Netflix.csv
marketing.csv
new_file.json
data.json
Netflix
shows.db
app.py
.vscode
purchase.csv
final.zip
sales.csv

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.