FSUtil: High-level File-System Operations
python-fsutil provides a collection of high-level, convenient utilities for common file-system operations, simplifying tasks like reading, writing, copying, moving, and deleting files and directories. It aims to offer a more Pythonic and less verbose alternative to direct `os` and `shutil` module usage. The current version is 0.16.1, and the library maintains an active release cadence with minor updates every few months.
Warnings
- gotcha Atomic file operations (fsutil.write_file with `atomic=True`) had known issues with preserving file permissions and exhibited inconsistent behavior on Windows in versions prior to 0.16.0. This could lead to incorrect permissions or data loss on specific platforms, or race conditions if not handled carefully.
- gotcha Search methods like `fsutil.search_files` and `fsutil.search_dirs` exhibited incorrect behavior when dealing with relative paths and sometimes failed to normalize paths using OS-specific separators in versions prior to 0.16.1. This could lead to unexpected results or missed files/directories in search operations.
- gotcha The `fsutil.join_filename` method could return incorrect or unexpected values when the `basename` or `extension` arguments were empty in versions prior to 0.14.0. This might affect applications relying on precise filename construction from components.
Install
-
pip install python-fsutil
Imports
- fsutil
import fsutil
Quickstart
import fsutil
import os
import tempfile
import pathlib
# Create a temporary directory for demonstration
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = pathlib.Path(tmp_dir)
file_path = tmp_path / "my_test_file.txt"
content = "Hello, fsutil!\nThis is a test file."
# 1. Write content to a file (atomic operation for safety)
fsutil.write_file(file_path, content, encoding="utf-8", atomic=True)
print(f"File written to: {file_path}")
# 2. Read content from the file
read_content = fsutil.read_file(file_path, encoding="utf-8")
print(f"Content read:\n---\n{read_content}---")
assert read_content == content
# 3. Check if file exists
assert fsutil.file_exists(file_path)
# 4. Get file size
size = fsutil.get_file_size(file_path)
print(f"File size: {size} bytes")
# 5. Create a nested directory
new_dir_path = tmp_path / "parent_dir" / "child_dir"
fsutil.create_dir(new_dir_path)
print(f"Directory created: {new_dir_path}")
assert fsutil.dir_exists(new_dir_path)
# 6. Remove the file
fsutil.remove_file(file_path)
assert not fsutil.file_exists(file_path)
print(f"File removed: {file_path}")
# 7. Remove the directory (recursively)
fsutil.remove_dir(tmp_path / "parent_dir")
assert not fsutil.dir_exists(tmp_path / "parent_dir")
print(f"Directory removed: {tmp_path / 'parent_dir'}")
print("fsutil quickstart completed successfully.")