os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned.
Syntax: os.listdir(path)
Parameters:
path (optional) : path of the directory
Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list.
Code #1: use of os.listdir() method
import os
path = "/"
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
print(dir_list)
|
Output:
Files and directories in ' / ' :
['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr',
'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']
Code #2: use of os.listdir() method
import os
path = os.getcwd()
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
print(dir_list)
|
Output:
Files and directories in ' /home/ihritik ' :
['.rstudio-desktop', '.gnome', '.ipython', '.cache', '.config', '.ssh', 'Public',
'Desktop', '.pki', 'R', '.bash_history', '.Rhistory', '.oracle_jre_usage', 'Music',
'.ICEauthority', 'Documents', 'examples.desktop', '.swipl-dir-history', '.local',
'.gnupg', '.profile', 'Pictures', '.keras', '.viminfo', '.thunderbird', 'Templates',
'.bashrc', '.bash_logout', '.sudo_as_admin_successful', 'Videos', 'images',
'tf_wx_model', 'Downloads', '.mozilla', 'geeksforgeeks']
Code #3: omitting path parameter
import os
dir_list = os.listdir()
print("Files and directories in current working directory :")
print(dir_list)
|
Output:
Files and directories in current working directory :
['.rstudio-desktop', '.gnome', '.ipython', '.cache', '.config', '.ssh', 'Public',
'Desktop', '.pki', 'R', '.bash_history', '.Rhistory', '.oracle_jre_usage', 'Music',
'.ICEauthority', 'Documents', 'examples.desktop', '.swipl-dir-history', '.local',
'.gnupg', '.profile', 'Pictures', '.keras', '.viminfo', '.thunderbird', 'Templates',
'.bashrc', '.bash_logout', '.sudo_as_admin_successful', 'Videos', 'images',
'tf_wx_model', 'Downloads', '.mozilla', 'geeksforgeeks']
As we can see the output of Code #2 and Code #3 are same. So if we omit the path parameter os.listdir() method will return the list of all files and directories in the current working directory.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!