Collections Module
The collections module provides advanced file system operations and enhanced data structures with comprehensive functionality for file management, recycling bin operations, and file system monitoring.
Key Components
FileStats: Enhanced data class for file statisticsFile: Enhanced file class with additional capabilitiesDirectory: Enhanced directory class with advanced operationsRecycleBin: Advanced recycling bin implementationOSUtils: Comprehensive OS utility classDummyFile: Template-based dummy file creator
File Management
FileStats
- class true.collections.FileStats(size, created, modified, accessed, permissions, is_hidden, mime_type, owner, group, is_symlink, symlink_target, md5_hash=None)[source]
Enhanced data class to hold file statistics
- __init__(size, created, modified, accessed, permissions, is_hidden, mime_type, owner, group, is_symlink, symlink_target, md5_hash=None)
File
Directory
- class true.collections.Directory(path, base_path=None)[source]
Enhanced directory class with additional capabilities
- zip_contents(output_path, compression=8)[source]
Create a zip archive of directory contents
- Return type:
Recycling Bin
RecycleBin
- class true.collections.RecycleBin(location, max_size=1073741824)[source]
Advanced RecycleBin implementation with extensive features.
- delete(path)[source]
Move item to recycle bin.
- Parameters:
path (
str) – Path to item to be deleted- Returns:
Item ID in recycle bin
- Return type:
- Raises:
StorageFullError – If recycle bin is full
FileNotFoundError – If item doesn’t exist
RecycleBinManager
OS Utilities
OSUtils
- class true.collections.OSUtils(base_path=None, max_workers=4)[source]
Enhanced OS utility class with comprehensive file system operations
- safe_move(src, dst, overwrite=False)[source]
Safely move a file or directory with retry mechanism
- Return type:
- batch_process(file_list, operation, parallel=True)[source]
Process multiple files in parallel or sequentially
- watch_directory(directory, callback)[source]
Watch a directory for changes and call callback on file events.
- stop_watching(directory=None)[source]
Stop watching a specific directory or all directories
- Return type:
- safe_delete(path, secure=False)[source]
Safely delete a file or directory with optional secure deletion.
- force_delete(path)[source]
Forcefully delete a file or directory, using extreme measures for both Unix and Windows.
- static _secure_delete_file(path, passes=3)[source]
Securely delete a file by overwriting its contents
- Return type:
- find_files_by_date(directory, start_date=None, end_date=None, modified=True)[source]
Find files within a date range.
File Creation
DummyFile
- class true.collections.DummyFile(default_size=1024, default_content=None)[source]
A class to manage the creation out for various types of dummy files using the Template Pattern.
- create_file(extension, filename=None, size=None, content=None)[source]
Generic method to create a dummy file based on the extension.
- Parameters:
extension – File extension (e.g., ‘.pdf’).
filename – Name of the file to create.
size – Size of the file in bytes.
content – Content to fill the file.
- custom_file(filename, extension, header=None, size=None, content=None)[source]
Create a custom dummy file.
- Parameters:
filename – Name of the file.
extension – File extension (e.g., ‘.custom’).
header – Custom header bytes.
size – Size of the file in bytes.
content – Custom content to fill the file.
FileCreator
- class true.collections.FileCreator(extension, default_size=1024, default_content=None)[source]
Abstract base class that defines the template for creating a dummy file.
- FILE_HEADERS = {'.7z': b"7z\xbc\xaf'\x1c", '.avi': b'RIFF', '.bmp': b'BM', '.docx': b'PK\x03\x04', '.epub': b'PK\x03\x04', '.gif': b'GIF89a', '.jpg': b'\xff\xd8\xff', '.mkv': b'\x1aE\xdf\xa3', '.mp3': b'ID3', '.mp4': b'ftyp', '.pdf': b'%PDF-1.4\n%', '.png': b'\x89PNG\r\n\x1a\n', '.rar': b'Rar!', '.svg': b'<?xml version="1.0"?>', '.tar': b'ustar', '.tiff': b'II*\x00', '.txt': b'', '.wav': b'RIFF', '.xlsx': b'PK\x03\x04', '.zip': b'PK\x03\x04'}
- __init__(extension, default_size=1024, default_content=None)[source]
Initialize the FileCreator instance.
- Parameters:
extension – File extension including dot (e.g., ‘.pdf’)
default_size – Default size of the dummy file in bytes.
default_content – Default content to fill the dummy file.
- create_file(filename=None, size=None, content=None)[source]
Template method to create a dummy file.
- Parameters:
filename – Name of the file to create.
size – Size of the file in bytes.
content – Content to fill the file.
- property header
Get the header bytes for the file type.
- property default_filename
Get the default filename for the file type.
Examples
File Operations
from true.collections import File, Directory, OSUtils
# Enhanced file operations
file = File("example.txt")
print(file.size) # Get file size
print(file.md5) # Get MD5 hash
print(file.mime_type) # Get MIME type
# Copy with retry mechanism
file.copy_to("backup/example.txt")
# Create backup
file.create_backup() # Creates example.txt.bak
# Directory operations
directory = Directory("my_folder")
directory.create() # Create if not exists
# Get directory tree
tree = directory.get_tree(max_depth=2)
# Create zip archive
directory.zip_contents("archive.zip")
Recycling Bin Usage
from true.collections import RecycleBin
# Initialize recycle bin
recycle_bin = RecycleBin("./trash", max_size=1024*1024*1024) # 1GB max
# Delete with move to recycle bin
item_id = recycle_bin.delete("old_file.txt")
# Restore from recycle bin
recycle_bin.restore(item_id)
# List items with pattern
items = recycle_bin.list_items("*.txt")
# Cleanup old items
recycle_bin.cleanup(days=30)
# Use as context manager for batch operations
with recycle_bin:
recycle_bin.delete("file1.txt")
recycle_bin.delete("file2.txt")
OS Utilities Usage
from true.collections import OSUtils
from datetime import datetime, timedelta
os_utils = OSUtils()
# Watch directory for changes
def on_change(event):
print(f"Change detected: {event.src_path}")
os_utils.watch_directory("watched_dir", on_change)
# Find files by date
yesterday = datetime.now() - timedelta(days=1)
files = os_utils.find_files_by_date(
"search_dir",
start_date=yesterday,
modified=True
)
# Safe delete with secure overwrite
os_utils.safe_delete("sensitive.txt", secure=True)
# Batch process files
def process_file(file_path):
# Process file
pass
os_utils.batch_process(
["file1.txt", "file2.txt"],
process_file,
parallel=True
)
Dummy File Creation
from true.collections import DummyFile
# Create dummy files of various types
dummy = DummyFile()
# Create PDF dummy file
dummy.create_file(".pdf", "test.pdf", size=1024*1024) # 1MB file
# Create image file
dummy.create_image("test.png")
# Create video file
dummy.create_video("output.mp4", fps=30)
# Create audio file
dummy.create_audio("test.wav", duration=5000)