The os.listdir path from the OS module in Python is used to fetch a list of files and directories at a specified path.
If the path argument is not provided, then it will return a list of files and directories from the current working directory.
Note: The
import osfrom the OS module in Python is used to interact with operating system commands.
os.listdir(path='.')
It has only one optional argument:
path: This is a path of the directory. The default path is the root directory.Note: Here, root directory means in the current working directory, where we can edit or program, if open into volatile memory.
It returns a list of files or directories present at a specified path.
Let's use os.listdir()in the code widget below:
# program to test os.listdir()# with or without argumentimport os# get files and directories in root directorypath = "/"# invoking os.listdir() with argumentlist_of_dir = os.listdir(path)print(f"Files & directories at {path}:")# print the list on consoleprint(list_of_dir)# get files and directories in current directory# invoking os.listdir() without argumentlist_of_dir = os.listdir()print(f"Files & directories at root :")# print the list on consoleprint(list_of_dir)
os.listdir() with an argument path='/' to get files and directories in current working directories.os.listdir() without arguments path='.' to get files and directories from the current working directory.Let's look at an example below with the current working directory:
# include os module in this programimport os# fetch the path of current working directorypath = os.getcwd()# get files and directories in current directory# invoking os.listdir() with argumentlist_of_dir = os.listdir(path)print(f"Files & directories at {path}:")# print the list consoleprint(list_of_dir)
getcwd() method to fetch the current working directory path.os.listdir() to return files and directories in a specified path.