Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Get Directory Listing Sorted by Name in Python



When we are dealing with large directories, managing files and folders is often required in listing them in a specific order. One common approach to list out the files/folders is sorting items by their names, which makes navigation and processing much easier.

Python simplifies this task with built-in modules such as os and pathlib, which allow developers to fetch and organize directory contents with just a few lines of code. In this article, we will go through the different methods to retrieve and sort directory listings alphabetically with clean and flexible solutions for our file-handling needs.

Using os.listdir() with sorted()

When os.listdir() method is combinedly used along with sorted() function in Python is one of the most simple and widely used methods to retrieve and alphabetically sort the contents of a directory. The os.listdir() method returns a list of all entries i.e., files and folders in a specific directory. The sorted() function will arrange the list of files/folders in alphabetical order.

Example

In this example, we are using os.listdir() and sorted() methods to retrieve and sort the directory files/folders of a defined directory ?

import os

# Define the target directory
directory = r'D:\Tutorialspoint'

# Get the list of items in the directory
items = os.listdir(directory)

# Sort the list alphabetically
sorted_items = sorted(items)

# Print the sorted items
for item in sorted_items:
    print(item)

Following is the output of the above program ?

Articles
Chainer
Image Recognition and Matching
Niharikaa_3month_work
Scipy

Using os.path.join()

As we discussed above os.listdir() method provides a list of files and folder names in a directory, which doesn't include their full path. If we want to get the complete paths, then we can use the os.path.join() along with sorted() function. The os.path.join() function ensures that the directory and file names are combined correctly across different operating systems.

Example

In this example, we are using os.listdir() along with os.path.join() and sorted() to get the full paths of items in a directory, sorted alphabetically by their names ?

import os

# Define the target directory
directory = r'D:\Tutorialspoint'

# Get the list of full paths
full_paths = [os.path.join(directory, item) for item in os.listdir(directory)]

# Sort by base name
sorted_paths = sorted(full_paths, key=lambda x: os.path.basename(x))

# Print the sorted full paths
for path in sorted_paths:
    print(path)

Below is the output of the above program ?

D:\Tutorialspoint\Articles
D:\Tutorialspoint\Chainer
D:\Tutorialspoint\Image Recognition and Matching
D:\Tutorialspoint\Niharikaa_3month_work
D:\Tutorialspoint\Scipy

Using pathlib.Path.iterdir()

The pathlib module is used to work with filesystem paths in Python. This module provides Path.iterdir() method which returns an iterator of Path objects representing the files and folders in a directory. By combining the pathlib.Path.iterdir() function with the sorted() function and by accessing the .name attribute, we can easily sort the directory contents alphabetically.

Example

Here in this example, we are using Path.iterdir() and sorted() to list and sort the contents of a directory by their names ?

from pathlib import Path

# Define the target directory
directory = Path(r'D:\Tutorialspoint')

# List and sort contents by name
sorted_items = sorted(directory.iterdir(), key=lambda x: x.name)

# Print sorted items
for item in sorted_items:
    print(item)

Following is the output of the above program ?

D:\Tutorialspoint\Articles
D:\Tutorialspoint\Chainer
D:\Tutorialspoint\Image Recognition and Matching
D:\Tutorialspoint\Niharikaa_3month_work
D:\Tutorialspoint\Scipy

Case-Insensitive Sorting

Python offers sorting with case sensitivity by default, i.e., uppercase letters are sorted before lowercase letters. We can convert all names to lowercase during sorting by using pathlib.Path.iterdir() with sorted() and the .lower() method on the file names, which ensures a case-insensitive alphabetical sort.

Example

In this example, we are sorting directory contents in a case-insensitive manner using Path.iterdir() and str.lower() ?

from pathlib import Path

# Define the target directory
directory = Path(r'D:\Tutorialspoint')

# List and sort contents by name, ignoring case
sorted_items = sorted(directory.iterdir(), key=lambda x: x.name.lower())

# Print sorted items
for item in sorted_items:
    print(item)

Here is the output of the above program ?

D:\Tutorialspoint\Articles
D:\Tutorialspoint\Chainer
D:\Tutorialspoint\chainer_env
D:\Tutorialspoint\example.py
D:\Tutorialspoint\Image Recognition and Matching
D:\Tutorialspoint\jpype_env
D:\Tutorialspoint\myenv
D:\Tutorialspoint\Niharikaa_3month_work
D:\Tutorialspoint\opennlp
D:\Tutorialspoint\sample
D:\Tutorialspoint\sample.py
D:\Tutorialspoint\Scipy
D:\Tutorialspoint\templates
PS D:\Tutorialspoint\Articles>

Natural Sorting

Natural sorting is also known as human sorting, which ensures that file names with numbers are ordered in a way that feels good to humans. For example, file2 should come before file10. In Python, we have the natsort library is specifically designed for Natural sorting, and when this is combined with pathlib.Path.iterdir() then it enables natural ordering of directory contents with ease.

Installing natsort

Before using natsort, we need to install it via pip through the command prompt -

pip install natsort

Example

In this example, we are using natsorted() from the natsort module to sort files naturally ?

from pathlib import Path
from natsort import natsorted

# Define the target directory
directory = Path(r'D:\Tutorialspoint')

# Get and naturally sort directory contents
sorted_items = natsorted(directory.iterdir(), key=lambda x: x.name)

# Print sorted items
for item in sorted_items:
    print(item)

Following is the output of the above program ?

D:\Tutorialspoint\Articles\file1.txt
D:\Tutorialspoint\Articles\file2.txt
Updated on: 2025-05-15T16:08:07+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements