DeaD_EyE icon

sort file_10.txt (kind of natsort)

DeaD_EyE | PRO | 07/04/22 11:29:26 AM UTC | 0 ⭐ | 1492 👁️ | Never ⏰ | []
Python |

980 B

|

None

|

0 👍

/

0 👎

"""
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)

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎