FSUtil: High-level File-System Operations

0.16.1 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates basic file and directory operations: creating a temporary file and directory, writing and reading file content, checking existence, getting file size, and finally cleaning up both the file and the created directory.

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.")

view raw JSON →