Created
August 12, 2025 14:15
-
-
Save ArthurDelannoyazerty/a23c75beacebc7040eabd2d8f2acc6ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""from . import FileUtils""" | |
from pathlib import Path | |
import os | |
import re | |
__all__ = ["FileUtils"] | |
class FileUtils: | |
def __init__(self): | |
"""This class is not meant to be instantiated.""" | |
raise NotImplementedError("FileUtils is a utility class and cannot be instantiated.") | |
@staticmethod | |
def find_files_scandir(directory: Path, extension:str='.zip') -> list[Path]: | |
def find_files_scandir_recursive(directory: Path, extension: str) -> list[Path]: | |
results = [] | |
try: | |
for entry in os.scandir(directory): | |
if entry.is_dir(follow_symlinks=False): | |
results.extend(find_files_scandir_recursive(Path(entry.path), extension)) # Recurse into subdirectories | |
elif entry.is_file(follow_symlinks=False) and entry.name.endswith(extension): | |
results.append(Path(entry.path)) | |
except (OSError, PermissionError): | |
pass | |
return results | |
return find_files_scandir_recursive(directory, extension) | |
@staticmethod | |
def sort_files_alphanumerically(files:list[Path]) -> list[Path]: | |
""" | |
Sort files alphanumerically, with numbers sorted numerically. | |
Example: | |
['1.zip', '10.zip', '11.zip', '2.zip', '7.zip', '7-8.zip', '9.zip'] -> ['1.zip', '2.zip', '7.zip', '7-8.zip', '9.zip', '10.zip', '11.zip'] | |
""" | |
def sort_key(file:Path): | |
num = re.search(r'(\d+)', str(file)).group(1) | |
num = num.replace('-', ' ') | |
num = int(num) if num.isdigit() else 0 | |
return (num, file) | |
return sorted(files, key=sort_key) | |
@staticmethod | |
def sort_files_by_date(files:list[Path]) -> list[Path]: | |
return sorted(files, key=lambda file: file.stat().st_mtime) | |
@staticmethod | |
def sort_files_by_size(files:list[Path]) -> list[Path]: | |
return sorted(files, key=lambda file: file.stat().st_size) | |
if __name__ == "__main__": | |
directory = Path('./example') | |
files = FileUtils.find_files_scandir(directory) | |
files = FileUtils.sort_files_by_size(files) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment