How to Use the Python os.listdir() Method

09/10/2021

Contents

In this article, you will learn how to use the Python os.listdir() method.

Python os.listdir() Method

The os.listdir() method in Python is used to get a list of filenames in a specified directory. The method returns a list of strings, where each string is a file or directory name in the specified directory.

Here’s an example of how you can use the os.listdir() method in Python:

import os

# get the list of filenames in the current directory
filenames = os.listdir(".")

# print each filename
for filename in filenames:
    print(filename)

In this example, the os.listdir(“.”) call gets a list of filenames in the current directory (represented by the “.”). The for loop then iterates over the list of filenames and prints each one.

You can specify a different directory by passing its path as the argument to os.listdir(). For example, os.listdir(“/home/user/documents”) would get a list of filenames in the /home/user/documents directory.

 

The os.listdir() method is very flexible and can be used in a number of different ways. Here are some additional details about the method:

Filtering the Results

You can filter the results of os.listdir() by using an if statement in the for loop. For example, you can display only the names of files that end with a specific extension:

import os

# get the list of filenames in the current directory
filenames = os.listdir(".")

# print each filename that ends with .txt
for filename in filenames:
    if filename.endswith(".txt"):
        print(filename)
Sorting the Results

By default, the os.listdir() method returns the filenames in an arbitrary order. If you need the filenames to be sorted in a specific order, you can use the sorted() function. For example, you can sort the filenames alphabetically:

import os

# get the list of filenames in the current directory
filenames = os.listdir(".")

# print each filename, sorted alphabetically
for filename in sorted(filenames):
    print(filename)
Directory and File Information

The os.listdir() method only returns the names of files and directories in a directory. If you need more information about the files and directories, such as their size, creation date, etc., you can use the os.stat() method. Here’s an example:

import os
import time

# get the list of filenames in the current directory
filenames = os.listdir(".")

# print each filename, modification time, and size
for filename in filenames:
    stat_info = os.stat(filename)
    print(f"{filename} - {time.ctime(stat_info.st_mtime)} - {stat_info.st_size} bytes")

These are just a few examples of what you can do with the os.listdir() method.