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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.