What is os.listdir() in python?
Overview
The os.listdir() method in Python gets the files and directories present in a given path.
Syntax
import os
os.listdir(path)
We need to import the os module to use the listdir() method.
Parameters
We provide path as a parameter to this function. By default, it takes the present directory as a path.
Returns
This method returns the list of files and directories in a given path.
Let us take a look at an example.
Example
#Import the OS moduleimport os#Get files in the current directoryprint(os.listdir())
Explanation
- Line 2: We import the
osmodule. This comes with methods likemkdir,listdir, etc. - Line 5: We print the files and directories in the current path using the
listdir()method.