Python Tutorial

As a Python developer one must know how to work and managing files. The OS module offers different functions and methods to work with files and folders.

In this tutorial I will walk you through how to list and sort files using the OS module in Python.

os.stat documentation

import os

# get current working directory
print(os.getcwd())

# list files in the current working directory
files = os.listdir(os.getcwd())
print(files)

# list files in the current working directory and sorted by
# file size (largest to smallest)
files.sort(key=lambda f: os.stat(f).st_size, reverse=True)
print(files)