How do you get a directory listing sorted by creation date in Python?

When working with files in Python, it's often useful to sort them based on their creation time. For example, to find the most recently added file or to process files in the order they were created. Python provides built-in modules such as os and pathlib which make it easy to retrieve file metadata and sort directory contents accordingly.

In this article, we will explore different methods to sort directory contents based on creation date in Python:

  • Using os.listdir() with sorted() and os.path.getctime()
  • Using os.scandir() with sorted() and stat()
  • Using pathlib.Path.iterdir() with sorted() and stat()
  • Using pathlib.Path.glob() with sorted() and stat()

Using os.listdir() with sorted() and os.path.getctime()

The os.listdir() function creates a list of items such as files and directories within a given directory. By using the sorted() function with a custom key that fetches the creation time of each item, we can sort this list by creation time using os.path.getctime().

Example

The following example demonstrates how to sort directory contents by creation time ?

import os
import tempfile

# Create a temporary directory with some test files
temp_dir = tempfile.mkdtemp()
test_files = ['file1.txt', 'file2.txt', 'file3.txt']

# Create test files
for file in test_files:
    with open(os.path.join(temp_dir, file), 'w') as f:
        f.write(f"Content of {file}")

def sorted_listing_by_creation_time(directory):
    def get_creation_time(item):
        item_path = os.path.join(directory, item)
        return os.path.getctime(item_path)
    
    items = os.listdir(directory)
    sorted_items = sorted(items, key=get_creation_time)
    return sorted_items

# Get sorted directory listing
result = sorted_listing_by_creation_time(temp_dir)
print("Files sorted by creation time:")
for file in result:
    print(file)

The output of the above code is ?

Files sorted by creation time:
file1.txt
file2.txt
file3.txt

Using os.scandir() with sorted() and stat()

The os.scandir() function is more efficient than os.listdir() for getting directory contents. It returns DirEntry objects that cache file metadata, reducing system calls.

Example

Here's how to list directory contents sorted by creation date using os.scandir() ?

import os
import tempfile

# Create a temporary directory with test files
temp_dir = tempfile.mkdtemp()
test_files = ['alpha.txt', 'beta.txt', 'gamma.txt']

for file in test_files:
    with open(os.path.join(temp_dir, file), 'w') as f:
        f.write(f"Content of {file}")

def sorted_directory_listing_by_creation_time_with_os_scandir(directory):
    def get_creation_time(entry):
        return entry.stat().st_ctime
    
    with os.scandir(directory) as entries:
        sorted_entries = sorted(entries, key=get_creation_time)
        sorted_items = [entry.name for entry in sorted_entries]
    return sorted_items

result = sorted_directory_listing_by_creation_time_with_os_scandir(temp_dir)
print("Files sorted by creation time:")
for file in result:
    print(file)

The output of the above code is ?

Files sorted by creation time:
alpha.txt
beta.txt
gamma.txt

Using pathlib.Path.iterdir() with sorted() and stat()

The pathlib module provides an object-oriented approach to file handling. We can use Path.iterdir() along with sorted() and stat() to list items and sort them by creation date.

Example

Below is an example using pathlib.Path.iterdir() to sort directory contents ?

from pathlib import Path
import tempfile

# Create a temporary directory with test files
temp_dir = tempfile.mkdtemp()
test_files = ['doc1.txt', 'doc2.txt', 'doc3.txt']

for file in test_files:
    Path(temp_dir, file).write_text(f"Content of {file}")

def sorted_directory(directory):
    def get_creation_time(item):
        return item.stat().st_ctime
    
    path_object = Path(directory)
    items = path_object.iterdir()
    sorted_items = sorted(items, key=get_creation_time)
    return [item.name for item in sorted_items]

result = sorted_directory(temp_dir)
print("Files sorted by creation time:")
for file in result:
    print(file)

The output of the above code is ?

Files sorted by creation time:
doc1.txt
doc2.txt
doc3.txt

Using pathlib.Path.glob() with sorted() and stat()

The Path.glob() method from the pathlib module returns an iterator of items matching a pattern. Using glob('*') matches all files and directories in the given path.

Example

The following example sorts directory contents using Path.glob() ?

from pathlib import Path
import tempfile

# Create a temporary directory with test files
temp_dir = tempfile.mkdtemp()
test_files = ['report1.txt', 'report2.txt', 'report3.txt']

for file in test_files:
    Path(temp_dir, file).write_text(f"Content of {file}")

def sorted_directory_glob(directory):
    def get_creation_time(item):
        return item.stat().st_ctime
    
    path_object = Path(directory)
    items = path_object.glob('*')
    sorted_items = sorted(items, key=get_creation_time)
    return [item.name for item in sorted_items]

result = sorted_directory_glob(temp_dir)
print("Files sorted by creation time:")
for file in result:
    print(file)

The output of the above code is ?

Files sorted by creation time:
report1.txt
report2.txt
report3.txt

Comparison of Methods

Method Performance Best For
os.listdir() Good Simple directory listing
os.scandir() Better Large directories, cached metadata
Path.iterdir() Good Object-oriented approach
Path.glob() Good Pattern matching and filtering

Conclusion

Python offers multiple approaches to sort directory contents by creation date. Use os.scandir() for better performance with large directories, or pathlib methods for cleaner, object-oriented code. All methods use the creation time from file metadata to sort entries chronologically.

Updated on: 2026-03-24T18:27:28+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements