Python os.listdir() Method Tutorial

Python provides the os module for operating system-related functions. The os.listdir() is a popular method used to list directories. The directories are listed for the current working directory or for the specified path. If no parameter is provided the current working path directories are listed.

os.listdir() Syntax

The os.listdir() method has very simple syntax where it only accepts a single parameter which is optional. To use the os.listdir() method the os module should be also imported.

import os

os.listdir(PATH)
  • PATH is the path on which directories will be listed. The PATH is an optional parameter.

Get Current Working Directory

Before listing the current working path directories it can be very useful to print the current working path. Hopefully the os.getcwd() is used to print the current working path.

import os 

print(os.getcwd())
/home/ismail

List Current Working Directory Folders

We can use the os.listdir() method in order to list directories for the current working directory or path. We do not need to provide any parameter to the listdir() method. We will also use the os.getcwd() method to print current working directory for more information.

import os 

print(os.getcwd())

print(os.listdir())
/home/ismail
['grep', 'Videos', 'Desktop', 'Templates', 'Music', 'notes.txt', 'phpinfo.php', 'nmap', 'snap', '.local', '.bashrc', '.python_history', '.cache', '.config', '.viminfo', '.profile', '.gnupg', '.lesshst', 'Public', 'Documents', 'Pictures', '.wget-hsts', '.sudo_as_admin_successful', '.ssh', 'Downloads', '.bash_history', '.bash_logout']

From the output, we can see that all normal and hidden directories are provided as a list.

List Specified Path Directories

The os.listdir() method can be also used to list directories for the specified path. In the following example, we list directories for the path “/etc/”.

import os 

print(os.listdir("/etc"))

Leave a Comment