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 os from 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 argument
import os
# get files and directories in root directory
path = "/"
# invoking os.listdir() with argument
list_of_dir = os.listdir(path)
print(f"Files & directories at {path}:")
# print the list on console
print(list_of_dir)
# get files and directories in current directory
# invoking os.listdir() without argument
list_of_dir = os.listdir()
print(f"Files & directories at root :")
# print the list on console
print(list_of_dir)

Code explanation

  • Line 7: We invoke os.listdir() with an argument path='/' 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 arguments path='.' 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 program
import os
# fetch the path of current working directory
path = os.getcwd()
# get files and directories in current directory
# invoking os.listdir() with argument
list_of_dir = os.listdir(path)
print(f"Files & directories at {path}:")
# print the list console
print(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.

Free Resources