How to list all current working directories in Python
Overview
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.
Syntax
os.listdir(path='.')
Parameters
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.
Return value
It returns a list of files or directories present at a specified path.
Code example 1
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)
Code explanation
- Line 7: We invoke
os.listdir()with an argumentpath='/'to get files and directories in current working directories. - Line 10: We print a list of files and directories in the root directory.
- Line 13: We invoke
os.listdir()without argumentspath='.'to get files and directories from the current working directory. - Line 16: We print a list of files and directories in the current working directory.
Code example 2
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)
Code explanation
- Line 4: We invoke the
getcwd()method to fetch the current working directory path. - Line 7: We use
os.listdir()to return files and directories in a specified path. - Line 10: We print files and directories in the current working directory.