Advertisement
DeaD_EyE

sort file_10.txt (kind of natsort)

Jul 4th, 2022
938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. """
  2. natsort with files which follows the pattern file_nn.xxx or file_nn (no extension)
  3. where nn is an integer and xxx the extension.
  4.  
  5. The files are sorted by: name, extension, value
  6. """
  7.  
  8. from __future__ import annotations
  9.  
  10. from pathlib import Path
  11. from typing import Iterable, TypeVar
  12.  
  13. T = TypeVar("T", str, Path)
  14.  
  15.  
  16. def natsort(iterable: Iterable[T], reverse=False) -> list[T]:
  17.     """
  18.    Sort the files by name, extension, integer
  19.    """
  20.  
  21.     def keyfunc(path: str | Path) -> tuple[str, str, int]:
  22.         """
  23.        Keyfunc takes a str or a path object and
  24.        returns (name: str, suffix: str, value: int)
  25.        """
  26.         path = Path(path)
  27.  
  28.         try:
  29.             name, number = path.stem.split("_")
  30.         except ValueError:
  31.             return path.name, path.suffix, -1
  32.  
  33.         return name, path.suffix, int(number)
  34.  
  35.     return sorted(iterable, key=keyfunc, reverse=reverse)
  36.  
  37.  
  38. ns = natsort(["file1.txt", "file_2.txt", "file_3.txt"])
  39. print(ns)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement