Python os.listdir() Method
os.listdir() Overview
The os.listdir() method is used to return a list of the names of the files or folders contained in the specified folder. This list is in alphabetical order. It does not include . and . even if it is in a folder.
Only supported under Unix, Windows.
os.listdir() Syntax
The listdir() method syntax format is as follows.
os.listdir(path)
os.listdir() Parameters
- path – the path to the directory to be listed
os.listdir() Return Value
Returns the list of files and folders under the specified path.
os.listdir() Demo#1
The following example demonstrates the use of the listdir() method.
# Python program to explain os.listdir() method in apidemos.com
# importing os module
import os
# Get the list of all files and directories
# in the root directory
path = "/root/"
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# print the list
print(dir_list)
Output:
os.listdir() Demo#2
If we do not specify any path os.listdir() method will return the list of all files and directories in current working directory.
# Python program to explain os.listdir() method in apidemos.com
# importing os module
import os
dir_list = os.listdir()
print("Files and directories in current working directory :")
# print the list
print(dir_list)
Output: