Python os listdir()

The os.listdir function in Python's os module returns a list of all entries (files and directories) in a specified directory. This function is useful for accessing and managing the contents of directories.

Table of Contents

  1. Introduction
  2. os.listdir Function Syntax
  3. Examples
    • Basic Usage
    • Listing Files in a Directory
  4. Real-World Use Case
  5. Conclusion

Introduction

The os.listdir function in Python's os module retrieves a list of the names of the entries in a given directory. This includes both files and directories. It is useful for tasks such as directory traversal, file management, and building directory-based applications.

os.listdir Function Syntax

Here is how you use the os.listdir function:

import os

entries = os.listdir(path)

Parameters:

  • path: The path to the directory. If path is not specified, the current working directory is used.

Returns:

  • A list of strings, each representing a name of an entry in the specified directory.

Examples

Basic Usage

Here is an example of how to use the os.listdir function to list the contents of a directory.

Example

import os

# Listing entries in the current directory
entries = os.listdir('.')
print(entries)

Output:

['file1.txt', 'file2.py', 'directory1', 'directory2']

Listing Files in a Directory

This example demonstrates how to list the contents of a specific directory.

Example

import os

# Listing entries in the '/home/user' directory
directory_path = '/home/user'
entries = os.listdir(directory_path)
print(entries)

Output:

['documents', 'photos', 'music', 'notes.txt', 'script.py']

Real-World Use Case

Filtering Files by Extension

In real-world applications, the os.listdir function can be used to filter files by their extension or other criteria.

Example

import os

def list_files_by_extension(directory, extension):
    return [file for file in os.listdir(directory) if file.endswith(extension)]

# Example usage
directory_path = '/home/user/documents'
extension = '.txt'
txt_files = list_files_by_extension(directory_path, extension)
print(txt_files)

Output:

['notes.txt', 'todo.txt', 'readme.txt']

Conclusion

The os.listdir function in Python's os module retrieves a list of entries in a specified directory. This function is useful for accessing and managing the contents of directories, enabling tasks such as directory traversal, file filtering, and building directory-based applications.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare