Pathmagic
Pathmagic provides Object-Relational Mapping (ORM) style path classes, `File` and `Dir`, which automatically execute file system I/O operations when their attributes are modified. This approach aims to abstract away common filesystem interactions, offering an intuitive way to manipulate files and directories, including easy content management for various file types. The library is currently at version 0.3.14 and maintains an active development pace with frequent minor releases.
Warnings
- breaking The `pathmagic` library is currently under active development, and its API is subject to significant changes that may introduce breaking changes in future versions. Code written with the current API may require adjustments.
- gotcha The documentation for `pathmagic` may fall out of sync with updates due to the rapid development pace. Users might encounter undocumented features or outdated examples.
- gotcha This `pathmagic` library (for ORM-like filesystem objects) is frequently confused with the `python-magic` library (a Python interface to the `libmagic` file type identification library). Ensure you are installing and importing the correct package for your intended use case.
Install
-
pip install pathmagic
Imports
- File
from pathmagic import File
- Dir
from pathmagic import Dir
Quickstart
from pathmagic import File, Dir
import os
# Ensure a directory exists for demonstration
temp_dir_name = "pathmagic_demo_dir"
if not os.path.exists(temp_dir_name):
os.makedirs(temp_dir_name)
print(f"Working in directory: {temp_dir_name}")
# 1. Create a File object and write content
my_file_path = os.path.join(temp_dir_name, "my_document.txt")
my_file = File(my_file_path)
my_file.content = "Hello, pathmagic world!\nThis is a test."
print(f"Created file at: {my_file.path} and wrote content.")
# 2. Read content from the File object
read_content = my_file.content
print(f"Read content: \"{read_content.strip()}\"")
# 3. Modify a file attribute, triggering a filesystem operation (e.g., rename)
old_path = my_file.path
my_file.name = "renamed_document.txt" # This automatically renames the file on disk
print(f"File renamed from '{old_path}' to '{my_file.path}'")
# 4. Demonstrate a Dir object
my_dir = Dir(temp_dir_name)
print(f"Directory object created for: {my_dir.path}")
# Clean up
os.remove(my_file.path)
os.rmdir(temp_dir_name)
print("Cleaned up demo files and directory.")