Skip to content

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 BaseFileOperations

Bases: FileParsingMixin, FileValidationMixin

Base class with common utilities for file operations.

Provides static methods for hash calculation, duplicate detection, safe file operations, and batch processing.

Source

batch_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

NameTypeDefaultDescription
filesList[str]List of file paths to rename.
rename_functionCallable[[str], str]Function that takes old name and returns new name.
dry_runboolFalseIf True, simulate without renaming.

Returns

  • Dict[str, Any]Report dictionary with total, renamed, errors, skipped lists.
Source

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

NameTypeDefaultDescription
file_pathstrPath to the file.
algorithmstr'md5'Hash algorithm ('md5', 'sha1', 'sha256').
chunk_sizeint8192Chunk size for reading in bytes.

Returns

  • strFile hash in hexadecimal, or empty string on error.
Source

clean_filenamestaticmethod

def clean_filename(filename: str, replace_char: str = '_') -> str:

Clean a filename by removing invalid characters.

Parameters

NameTypeDefaultDescription
filenamestrFilename to clean.
replace_charstr'_'Character to replace invalid chars with.

Returns

  • strCleaned filename safe for file systems.
Source

create_backupstaticmethod

def create_backup(
file_path: str,
backup_dir: Optional[str] = None,
) -> Optional[str]:

Create a backup of a file.

Parameters

NameTypeDefaultDescription
file_pathstrPath to the file to backup.
backup_dirOptional[str]NoneBackup folder path (None = same directory).

Returns

  • Optional[str]Created backup path, or None on error.
Source

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

NameTypeDefaultDescription
directorystrDirectory path to analyze.
extensionsList[str]File extensions to consider.
recursiveboolTrueWhether to search recursively.
by_hashboolTrueCompare by file hash (more accurate).
by_sizeboolFalseCompare by file size (faster).

Returns

  • Dict[str, List[str]]Dictionary mapping keys to lists of duplicate file paths.
Source

format_sizestaticmethod

def format_size(size_bytes: float) -> str:

Format a size in bytes to human readable format.

Parameters

NameTypeDescription
size_bytesfloatSize in bytes.

Returns

  • strFormatted size string (e.g., '1.5 GB').
Source

get_directory_sizestaticmethod

def get_directory_size(directory: str) -> int:

Calculate the total size of a directory.

Parameters

NameTypeDescription
directorystrDirectory path to analyze.

Returns

  • intTotal size in bytes.
Source

get_file_infostaticmethod

def get_file_info(file_path: str) -> Dict[str, Any]:

Retrieve file information.

Parameters

NameTypeDescription
file_pathstrPath to the file.

Returns

  • Dict[str, Any]Dictionary with file metadata (size, dates, etc.).
Source

safe_copystaticmethod

def safe_copy(
source: str,
destination: str,
overwrite: bool = False,
create_dirs: bool = True,
) -> bool:

Copy a file safely.

Parameters

NameTypeDefaultDescription
sourcestrSource file path.
destinationstrDestination file path.
overwriteboolFalseWhether to overwrite existing files.
create_dirsboolTrueWhether to create parent directories.

Returns

  • boolTrue if successful, False otherwise.
Source

safe_movestaticmethod

def safe_move(
source: str,
destination: str,
overwrite: bool = False,
create_dirs: bool = True,
) -> bool:

Move a file safely.

Parameters

NameTypeDefaultDescription
sourcestrSource file path.
destinationstrDestination file path.
overwriteboolFalseWhether to overwrite existing files.
create_dirsboolTrueWhether to create parent directories.

Returns

  • boolTrue if successful, False otherwise.
Source

HardLinkError

class HardLinkError

Bases: OSError

A hard link could not be made, such as between two drives.

Source

Functions

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

NameTypeDescription
sourcestrAn existing file.
folderstrAn existing folder.
Source

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

NameTypeDescription
pathstrThe folder.
Source

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

NameTypeDefaultDescription
sourcestrSource file path.
destinationstrDestination file path.
backupboolFalseWhether to keep the replaced file as '.backup'.
followsOptional[str]NoneNew path of the file this one goes with, such as the video of a subtitle; undoing that file puts this one back too.
modestrMOVEMOVE, 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.
Source

Attributes

NameValue
loggerlogging.getLogger(__name__)
Built with Kiln