Skip to content

FileObject API Reference

API documentation

hands_scaphoid.objects.FileObject

File operations module for hands-scaphoid package.

This module provides the File class for pure file operations without context management.

File

name: FileObject.py uuid: 63856607-707d-4e3b-8e15-3d81661086b0 date: 2025-09-16

Description

Pure file operations class - no context management

Project

name: hands_scaphoid uuid: 2945ba3b-2d66-4dff-b898-672c386f03f4 url: https://github.com/42sol-eu/hands_scaphoid

Authors: ["Andreas Häberle"]

Classes

FileObject

Bases: ObjectItem

Represents a file in the shell context. Pure file operations class without context management.

This class provides static methods for file operations that can be used independently of any context manager. All methods operate on explicit file paths and do not maintain any state.

Example
Direct file operations

File.write_content(Path("config.txt"), "setting=value") content = File.read_content(Path("config.txt")) File.append_line(Path("log.txt"), "New log entry")

Attributes:

Name Type Description
name str

The name of the file.

path str

The path of the file in the filesystem.

Source code in src/hands_scaphoid/objects/FileObject.py
class FileObject(ObjectItem):
    """
    Represents a file in the shell context.
    Pure file operations class without context management.

    This class provides static methods for file operations that can be used
    independently of any context manager. All methods operate on explicit
    file paths and do not maintain any state.

    Example:
        # Direct file operations
        File.write_content(Path("config.txt"), "setting=value")
        content = File.read_content(Path("config.txt"))
        File.append_line(Path("log.txt"), "New log entry")

    Attributes:
        name (str): The name of the file.
        path (str): The path of the file in the filesystem.
    """

    def __init__(self, name: str, path: str):
        super().__init__(name, path, item_type=ItemType.FILE)

    def __repr__(self):
        return f"FileObject(name={self.name}, path={self.path})"

    @staticmethod
    def read_content(file_path: PathLike) -> str:
        """
        Read the entire content of a file.

        Args:
            file_path: Path to the file to read

        Returns:
            File content as string

        Raises:
            FileNotFoundError: If the file doesn't exist
            PermissionError: If lacking read permissions
        """
        path = Path(file_path)
        try:
            with open(path, "r", encoding="utf-8") as f:
                return f.read()
        except FileNotFoundError:
            console.print(f"[red]File not found:[/red] {path}")
            raise
        except PermissionError:
            console.print(f"[red]Permission denied reading file:[/red] {path}")
            raise
        except Exception as e:
            console.print(f"[red]Error reading file {path}:[/red] {e}")
            raise

    @staticmethod
    def read_lines(file_path: PathLike) -> List[str]:
        """
        Read all lines from a file.

        Args:
            file_path: Path to the file to read

        Returns:
            List of lines from the file
        """
        path = Path(file_path)
        try:
            with open(path, "r", encoding="utf-8") as f:
                return f.readlines()
        except FileNotFoundError:
            console.print(f"[red]File not found:[/red] {path}")
            raise
        except PermissionError:
            console.print(f"[red]Permission denied reading file:[/red] {path}")
            raise
        except Exception as e:
            console.print(f"[red]Error reading file {path}:[/red] {e}")
            raise

    @staticmethod
    def write_content(
        file_path: PathLike, content: str, create_dirs: bool = True
    ) -> None:
        """
        Write content to a file, replacing existing content.

        Args:
            file_path: Path to the file to write
            content: Content to write to the file
            create_dirs: Whether to create parent directories if they don't exist

        Raises:
            PermissionError: If lacking write permissions
        """
        path = Path(file_path)
        try:
            if create_dirs:
                path.parent.mkdir(parents=True, exist_ok=True)

            with open(path, "w", encoding="utf-8") as f:
                f.write(content)

            console.print(f"[green]Wrote content to file:[/green] {path}")
        except PermissionError:
            console.print(f"[red]Permission denied writing file:[/red] {path}")
            raise
        except Exception as e:
            console.print(f"[red]Error writing file {path}:[/red] {e}")
            raise

    @staticmethod
    def append_content(
        file_path: PathLike, content: str, create_dirs: bool = True
    ) -> None:
        """
        Append content to a file.

        Args:
            file_path: Path to the file to append to
            content: Content to append to the file
            create_dirs: Whether to create parent directories if they don't exist
        """
        path = Path(file_path)
        try:
            if create_dirs:
                path.parent.mkdir(parents=True, exist_ok=True)

            with open(path, "a", encoding="utf-8") as f:
                f.write(content)

            console.print(f"[green]Appended content to file:[/green] {path}")
        except PermissionError:
            console.print(f"[red]Permission denied writing file:[/red] {path}")
            raise
        except Exception as e:
            console.print(f"[red]Error writing file {path}:[/red] {e}")
            raise

    @staticmethod
    def write_line(file_path: PathLike, line: str, create_dirs: bool = True) -> None:
        """
        Write a line to a file, replacing existing content.

        Args:
            file_path: Path to the file to write
            line: Line to write to the file (newline will be added)
            create_dirs: Whether to create parent directories if they don't exist
        """
        content = line if line.endswith("\n") else line + "\n"
        FileObject.write_content(file_path, content, create_dirs)

    @staticmethod
    def append_line(file_path: PathLike, line: str, create_dirs: bool = True) -> None:
        """
        Append a line to a file.

        Args:
            file_path: Path to the file to append to
            line: Line to append to the file (newline will be added)
            create_dirs: Whether to create parent directories if they don't exist
        """
        content = line if line.endswith("\n") else line + "\n"
        FileObject.append_content(file_path, content, create_dirs)

    @staticmethod
    def add_heading(
        file_path: PathLike, title: str, level: int = 1, create_dirs: bool = True
    ) -> None:
        """
        Append a markdown-style heading to a file.

        Args:
            file_path: Path to the file to append to
            title: Heading text
            level: Heading level (1-6)
            create_dirs: Whether to create parent directories if they don't exist
        """
        if not 1 <= level <= 6:
            raise ValueError("Heading level must be between 1 and 6")

        heading = "#" * level + " " + title + "\n"
        FileObject.append_content(file_path, heading, create_dirs)

    @staticmethod
    def create_file(file_path: PathLike, create_dirs: bool = True) -> None:
        """
        Create an empty file.

        Args:
            file_path: Path to the file to create
            create_dirs: Whether to create parent directories if they don't exist
        """
        path = Path(file_path)
        try:
            if create_dirs:
                path.parent.mkdir(parents=True, exist_ok=True)

            path.touch()
            console.print(f"[green]Created file:[/green] {path}")
        except PermissionError:
            console.print(f"[red]Permission denied creating file:[/red] {path}")
            raise
        except Exception as e:
            console.print(f"[red]Error creating file {path}:[/red] {e}")
            raise

    @staticmethod
    def file_exists(file_path: PathLike) -> bool:
        """
        Check if a file exists.

        Args:
            file_path: Path to check

        Returns:
            True if file exists and is a file, False otherwise
        """
        path = Path(file_path)
        return path.exists() and path.is_file()

    @staticmethod
    def get_file_size(file_path: PathLike) -> int:
        """
        Get the size of a file in bytes.

        Args:
            file_path: Path to the file

        Returns:
            File size in bytes

        Raises:
            FileNotFoundError: If the file doesn't exist
        """
        path = Path(file_path)
        if not path.exists():
            raise FileNotFoundError(f"File not found: {path}")
        return path.stat().st_size

    @staticmethod
    def copy_file(
        source_path: PathLike, target_path: PathLike, create_dirs: bool = True
    ) -> None:
        """
        Copy a file from source to target.

        Args:
            source_path: Path to the source file
            target_path: Path to the target file
            create_dirs: Whether to create target parent directories if they don't exist
        """

        source = Path(source_path)
        target = Path(target_path)

        if not source.exists():
            raise FileNotFoundError(f"Source file not found: {source}")

        try:
            if create_dirs:
                target.parent.mkdir(parents=True, exist_ok=True)

            shutil.copy2(source, target)
            console.print(f"[green]Copied file:[/green] {source}{target}")
        except PermissionError:
            console.print(
                f"[red]Permission denied copying file:[/red] {source}{target}"
            )
            raise
        except Exception as e:
            console.print(f"[red]Error copying file {source}{target}:[/red] {e}")
            raise

    @staticmethod
    def delete_file(file_path: PathLike) -> None:
        """
        Delete a file.

        Args:
            file_path: Path to the file to delete

        Raises:
            FileNotFoundError: If the file doesn't exist
            PermissionError: If lacking delete permissions
        """
        path = Path(file_path)
        try:
            if not path.exists():
                raise FileNotFoundError(f"File not found: {path}")

            path.unlink()
            console.print(f"[green]Deleted file:[/green] {path}")
        except PermissionError:
            console.print(f"[red]Permission denied deleting file:[/red] {path}")
            raise
        except Exception as e:
            console.print(f"[red]Error deleting file {path}:[/red] {e}")
            raise
Functions
read_content(file_path) staticmethod

Read the entire content of a file.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to read

required

Returns:

Type Description
str

File content as string

Raises:

Type Description
FileNotFoundError

If the file doesn't exist

PermissionError

If lacking read permissions

Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def read_content(file_path: PathLike) -> str:
    """
    Read the entire content of a file.

    Args:
        file_path: Path to the file to read

    Returns:
        File content as string

    Raises:
        FileNotFoundError: If the file doesn't exist
        PermissionError: If lacking read permissions
    """
    path = Path(file_path)
    try:
        with open(path, "r", encoding="utf-8") as f:
            return f.read()
    except FileNotFoundError:
        console.print(f"[red]File not found:[/red] {path}")
        raise
    except PermissionError:
        console.print(f"[red]Permission denied reading file:[/red] {path}")
        raise
    except Exception as e:
        console.print(f"[red]Error reading file {path}:[/red] {e}")
        raise
read_lines(file_path) staticmethod

Read all lines from a file.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to read

required

Returns:

Type Description
List[str]

List of lines from the file

Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def read_lines(file_path: PathLike) -> List[str]:
    """
    Read all lines from a file.

    Args:
        file_path: Path to the file to read

    Returns:
        List of lines from the file
    """
    path = Path(file_path)
    try:
        with open(path, "r", encoding="utf-8") as f:
            return f.readlines()
    except FileNotFoundError:
        console.print(f"[red]File not found:[/red] {path}")
        raise
    except PermissionError:
        console.print(f"[red]Permission denied reading file:[/red] {path}")
        raise
    except Exception as e:
        console.print(f"[red]Error reading file {path}:[/red] {e}")
        raise
write_content(file_path, content, create_dirs=True) staticmethod

Write content to a file, replacing existing content.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to write

required
content str

Content to write to the file

required
create_dirs bool

Whether to create parent directories if they don't exist

True

Raises:

Type Description
PermissionError

If lacking write permissions

Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def write_content(
    file_path: PathLike, content: str, create_dirs: bool = True
) -> None:
    """
    Write content to a file, replacing existing content.

    Args:
        file_path: Path to the file to write
        content: Content to write to the file
        create_dirs: Whether to create parent directories if they don't exist

    Raises:
        PermissionError: If lacking write permissions
    """
    path = Path(file_path)
    try:
        if create_dirs:
            path.parent.mkdir(parents=True, exist_ok=True)

        with open(path, "w", encoding="utf-8") as f:
            f.write(content)

        console.print(f"[green]Wrote content to file:[/green] {path}")
    except PermissionError:
        console.print(f"[red]Permission denied writing file:[/red] {path}")
        raise
    except Exception as e:
        console.print(f"[red]Error writing file {path}:[/red] {e}")
        raise
append_content(file_path, content, create_dirs=True) staticmethod

Append content to a file.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to append to

required
content str

Content to append to the file

required
create_dirs bool

Whether to create parent directories if they don't exist

True
Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def append_content(
    file_path: PathLike, content: str, create_dirs: bool = True
) -> None:
    """
    Append content to a file.

    Args:
        file_path: Path to the file to append to
        content: Content to append to the file
        create_dirs: Whether to create parent directories if they don't exist
    """
    path = Path(file_path)
    try:
        if create_dirs:
            path.parent.mkdir(parents=True, exist_ok=True)

        with open(path, "a", encoding="utf-8") as f:
            f.write(content)

        console.print(f"[green]Appended content to file:[/green] {path}")
    except PermissionError:
        console.print(f"[red]Permission denied writing file:[/red] {path}")
        raise
    except Exception as e:
        console.print(f"[red]Error writing file {path}:[/red] {e}")
        raise
write_line(file_path, line, create_dirs=True) staticmethod

Write a line to a file, replacing existing content.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to write

required
line str

Line to write to the file (newline will be added)

required
create_dirs bool

Whether to create parent directories if they don't exist

True
Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def write_line(file_path: PathLike, line: str, create_dirs: bool = True) -> None:
    """
    Write a line to a file, replacing existing content.

    Args:
        file_path: Path to the file to write
        line: Line to write to the file (newline will be added)
        create_dirs: Whether to create parent directories if they don't exist
    """
    content = line if line.endswith("\n") else line + "\n"
    FileObject.write_content(file_path, content, create_dirs)
append_line(file_path, line, create_dirs=True) staticmethod

Append a line to a file.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to append to

required
line str

Line to append to the file (newline will be added)

required
create_dirs bool

Whether to create parent directories if they don't exist

True
Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def append_line(file_path: PathLike, line: str, create_dirs: bool = True) -> None:
    """
    Append a line to a file.

    Args:
        file_path: Path to the file to append to
        line: Line to append to the file (newline will be added)
        create_dirs: Whether to create parent directories if they don't exist
    """
    content = line if line.endswith("\n") else line + "\n"
    FileObject.append_content(file_path, content, create_dirs)
add_heading(file_path, title, level=1, create_dirs=True) staticmethod

Append a markdown-style heading to a file.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to append to

required
title str

Heading text

required
level int

Heading level (1-6)

1
create_dirs bool

Whether to create parent directories if they don't exist

True
Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def add_heading(
    file_path: PathLike, title: str, level: int = 1, create_dirs: bool = True
) -> None:
    """
    Append a markdown-style heading to a file.

    Args:
        file_path: Path to the file to append to
        title: Heading text
        level: Heading level (1-6)
        create_dirs: Whether to create parent directories if they don't exist
    """
    if not 1 <= level <= 6:
        raise ValueError("Heading level must be between 1 and 6")

    heading = "#" * level + " " + title + "\n"
    FileObject.append_content(file_path, heading, create_dirs)
create_file(file_path, create_dirs=True) staticmethod

Create an empty file.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to create

required
create_dirs bool

Whether to create parent directories if they don't exist

True
Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def create_file(file_path: PathLike, create_dirs: bool = True) -> None:
    """
    Create an empty file.

    Args:
        file_path: Path to the file to create
        create_dirs: Whether to create parent directories if they don't exist
    """
    path = Path(file_path)
    try:
        if create_dirs:
            path.parent.mkdir(parents=True, exist_ok=True)

        path.touch()
        console.print(f"[green]Created file:[/green] {path}")
    except PermissionError:
        console.print(f"[red]Permission denied creating file:[/red] {path}")
        raise
    except Exception as e:
        console.print(f"[red]Error creating file {path}:[/red] {e}")
        raise
file_exists(file_path) staticmethod

Check if a file exists.

Parameters:

Name Type Description Default
file_path PathLike

Path to check

required

Returns:

Type Description
bool

True if file exists and is a file, False otherwise

Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def file_exists(file_path: PathLike) -> bool:
    """
    Check if a file exists.

    Args:
        file_path: Path to check

    Returns:
        True if file exists and is a file, False otherwise
    """
    path = Path(file_path)
    return path.exists() and path.is_file()
get_file_size(file_path) staticmethod

Get the size of a file in bytes.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file

required

Returns:

Type Description
int

File size in bytes

Raises:

Type Description
FileNotFoundError

If the file doesn't exist

Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def get_file_size(file_path: PathLike) -> int:
    """
    Get the size of a file in bytes.

    Args:
        file_path: Path to the file

    Returns:
        File size in bytes

    Raises:
        FileNotFoundError: If the file doesn't exist
    """
    path = Path(file_path)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {path}")
    return path.stat().st_size
copy_file(source_path, target_path, create_dirs=True) staticmethod

Copy a file from source to target.

Parameters:

Name Type Description Default
source_path PathLike

Path to the source file

required
target_path PathLike

Path to the target file

required
create_dirs bool

Whether to create target parent directories if they don't exist

True
Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def copy_file(
    source_path: PathLike, target_path: PathLike, create_dirs: bool = True
) -> None:
    """
    Copy a file from source to target.

    Args:
        source_path: Path to the source file
        target_path: Path to the target file
        create_dirs: Whether to create target parent directories if they don't exist
    """

    source = Path(source_path)
    target = Path(target_path)

    if not source.exists():
        raise FileNotFoundError(f"Source file not found: {source}")

    try:
        if create_dirs:
            target.parent.mkdir(parents=True, exist_ok=True)

        shutil.copy2(source, target)
        console.print(f"[green]Copied file:[/green] {source}{target}")
    except PermissionError:
        console.print(
            f"[red]Permission denied copying file:[/red] {source}{target}"
        )
        raise
    except Exception as e:
        console.print(f"[red]Error copying file {source}{target}:[/red] {e}")
        raise
delete_file(file_path) staticmethod

Delete a file.

Parameters:

Name Type Description Default
file_path PathLike

Path to the file to delete

required

Raises:

Type Description
FileNotFoundError

If the file doesn't exist

PermissionError

If lacking delete permissions

Source code in src/hands_scaphoid/objects/FileObject.py
@staticmethod
def delete_file(file_path: PathLike) -> None:
    """
    Delete a file.

    Args:
        file_path: Path to the file to delete

    Raises:
        FileNotFoundError: If the file doesn't exist
        PermissionError: If lacking delete permissions
    """
    path = Path(file_path)
    try:
        if not path.exists():
            raise FileNotFoundError(f"File not found: {path}")

        path.unlink()
        console.print(f"[green]Deleted file:[/green] {path}")
    except PermissionError:
        console.print(f"[red]Permission denied deleting file:[/red] {path}")
        raise
    except Exception as e:
        console.print(f"[red]Error deleting file {path}:[/red] {e}")
        raise