""" natsort with files which follows the pattern file_nn.xxx or file_nn (no extension) where nn is an integer and xxx the extension. The files are sorted by: name, extension, value """ from __future__ import annotations from pathlib import Path from typing import Iterable, TypeVar T = TypeVar("T", str, Path) def natsort(iterable: Iterable[T], reverse=False) -> list[T]: """ Sort the files by name, extension, integer """ def keyfunc(path: str | Path) -> tuple[str, str, int]: """ Keyfunc takes a str or a path object and returns (name: str, suffix: str, value: int) """ path = Path(path) try: name, number = path.stem.split("_") except ValueError: return path.name, path.suffix, -1 return name, path.suffix, int(number) return sorted(iterable, key=keyfunc, reverse=reverse) ns = natsort(["file1.txt", "file_2.txt", "file_3.txt"]) print(ns)