sok.file_operations.base_operations
Base operations common to all media types.
This module provides the BaseFileOperations class that combines parsing and validation mixins with concrete file operations:
- Hash calculation
- Duplicate detection
- Safe move/copy
- Batch renaming
- Backup creation
BaseFileOperations
class BaseFileOperationsBases: FileParsingMixin, FileValidationMixin
Base class with common utilities for file operations.
Provides static methods for hash calculation, duplicate detection, safe file operations, and batch processing.
Sourcebatch_renamestaticmethod
def batch_rename( files: List[str], rename_function: Callable[[str], str], dry_run: bool = False,) -> Dict[str, Any]:Rename multiple files using a rename function.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
files | List[str] | List of file paths to rename. | |
rename_function | Callable[[str], str] | Function that takes old name and returns new name. | |
dry_run | bool | False | If True, simulate without renaming. |
Returns
Dict[str, Any]Report dictionary with total, renamed, errors, skipped lists.
calculate_file_hashstaticmethod
def calculate_file_hash( file_path: str, algorithm: str = 'md5', chunk_size: int = 8192,) -> str:Calculate the hash of a file.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
file_path | str | Path to the file. | |
algorithm | str | 'md5' | Hash algorithm ('md5', 'sha1', 'sha256'). |
chunk_size | int | 8192 | Chunk size for reading in bytes. |
Returns
strFile hash in hexadecimal, or empty string on error.
clean_filenamestaticmethod
def clean_filename(filename: str, replace_char: str = '_') -> str:Clean a filename by removing invalid characters.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
filename | str | Filename to clean. | |
replace_char | str | '_' | Character to replace invalid chars with. |
Returns
strCleaned filename safe for file systems.
create_backupstaticmethod
def create_backup( file_path: str, backup_dir: Optional[str] = None,) -> Optional[str]:Create a backup of a file.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
file_path | str | Path to the file to backup. | |
backup_dir | Optional[str] | None | Backup folder path (None = same directory). |
Returns
Optional[str]Created backup path, or None on error.
find_duplicatesstaticmethod
def find_duplicates( directory: str, extensions: List[str], recursive: bool = True, by_hash: bool = True, by_size: bool = False,) -> Dict[str, List[str]]:Find duplicate files in a directory.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
directory | str | Directory path to analyze. | |
extensions | List[str] | File extensions to consider. | |
recursive | bool | True | Whether to search recursively. |
by_hash | bool | True | Compare by file hash (more accurate). |
by_size | bool | False | Compare by file size (faster). |
Returns
Dict[str, List[str]]Dictionary mapping keys to lists of duplicate file paths.
format_sizestaticmethod
def format_size(size_bytes: float) -> str:Format a size in bytes to human readable format.
Parameters
| Name | Type | Description |
|---|---|---|
size_bytes | float | Size in bytes. |
Returns
strFormatted size string (e.g., '1.5 GB').
get_directory_sizestaticmethod
def get_directory_size(directory: str) -> int:Calculate the total size of a directory.
Parameters
| Name | Type | Description |
|---|---|---|
directory | str | Directory path to analyze. |
Returns
intTotal size in bytes.
get_file_infostaticmethod
def get_file_info(file_path: str) -> Dict[str, Any]:Retrieve file information.
Parameters
| Name | Type | Description |
|---|---|---|
file_path | str | Path to the file. |
Returns
Dict[str, Any]Dictionary with file metadata (size, dates, etc.).
safe_copystaticmethod
def safe_copy( source: str, destination: str, overwrite: bool = False, create_dirs: bool = True,) -> bool:Copy a file safely.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
source | str | Source file path. | |
destination | str | Destination file path. | |
overwrite | bool | False | Whether to overwrite existing files. |
create_dirs | bool | True | Whether to create parent directories. |
Returns
boolTrue if successful, False otherwise.
safe_movestaticmethod
def safe_move( source: str, destination: str, overwrite: bool = False, create_dirs: bool = True,) -> bool:Move a file safely.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
source | str | Source file path. | |
destination | str | Destination file path. | |
overwrite | bool | False | Whether to overwrite existing files. |
create_dirs | bool | True | Whether to create parent directories. |
Returns
boolTrue if successful, False otherwise.
HardLinkError
class HardLinkErrorBases: OSError
A hard link could not be made, such as between two drives.
SourceFunctions
can_hard_link
def can_hard_link(source: str, folder: str) -> bool:Whether a hard link of a file can be made in a folder.
Makes a test link and deletes it: two drives, two Docker mounts, or a disk without hard links (FAT, exFAT, most network shares) say no.
Parameters
| Name | Type | Description |
|---|---|---|
source | str | An existing file. |
folder | str | An existing folder. |
make_folders
def make_folders(path: str) -> None:Create a folder and its missing parents, like os.makedirs.
The folders created are reported to the rename history, which removes them when the rename is undone and they are empty.
Parameters
| Name | Type | Description |
|---|---|---|
path | str | The folder. |
move_file
def move_file( source: str, destination: str, backup: bool = False, follows: Optional[str] = None, mode: str = MOVE,) -> Optional[str]:Move, hard link or copy a file, replacing the destination if it exists.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
source | str | Source file path. | |
destination | str | Destination file path. | |
backup | bool | False | Whether to keep the replaced file as ' |
follows | Optional[str] | None | New path of the file this one goes with, such as the video of a subtitle; undoing that file puts this one back too. |
mode | str | MOVE | MOVE, LINK (the source stays, for torrents that keep seeding) or COPY. A link that fails is an error, never a copy. |
Returns
Optional[str]Path of the created backup, or None if no backup was made.
Raises
HardLinkErrorIf the link cannot be made.OSErrorIf the move fails. A backup made for this move is restored.
Attributes
| Name | Value |
|---|---|
logger | logging.getLogger(__name__) |