Python os.listdir() Method



The Python os.listdir() method returns a list containing the names of the files within the given directory. The list will be in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

When listdir() is invoked without any arguments, it displays the current working directory.

Syntax

Following is the syntax for Python os.listdir() method −

os.listdir(path)

Parameters

The Python os.listdir() method accepts a single parameter −

  • path − It is an optional parameter that specify the directory, which needs to be explored.

Return Value

The Python os.listdir() method returns a list containing the names of the entries in the directory given by path.

Example

The following example shows the usage of listdir() method. Here, we are displaying files and directories available in the path "/home/TP".

import os, sys

# Open a file
path = "/home/TP"
dirs = os.listdir( path )

# Print all the files and directories
for file in dirs:
   print(file)

When we run above program, it produces following result −

Desktop
Pictures
Templates
.bash_history
Python
Music
.cache
.bashrc
Documents
Videos
Public
Downloads
.local

Example

In the following example, we are using the listdir() without passing any arguments. It will show the directories of the current working directory.

import os

# Listing only directories from current directory
print("Directories from the current directory:") 
drctry = [item for item in os.listdir() if os.path.isdir(item)]
print(drctry)

On running, the above program will produce the following result −

Directories from the current directory:
['new', 'tmp', 'Tutorials']
python_files_io.htm
Advertisements