all2md.utils.io_utils
I/O utilities for handling output destinations.
This module provides centralized utilities for writing content to various output destinations (files, file-like objects, or returning as file-like objects).
- all2md.utils.io_utils.backup_file(path: Path) Path | None
Copy
pathto a sibling backup file before it is overwritten.Tries
<path>.bakfirst; if that is taken, falls back to<path>.bak.1,<path>.bak.2, … until a free name is found. Returns the chosen backup path, orNoneifpathdoes not exist (in which case there is nothing to back up).- Parameters:
path (Path) – File that is about to be overwritten.
- Returns:
Path to the created backup, or None if no backup was needed.
- Return type:
Path or None
- all2md.utils.io_utils.write_content(content: str | bytes, output: str | Path | IO[bytes] | IO[str] | None) StringIO | BytesIO | None
Write content to output destination or return as file-like object.
This function provides a centralized way to handle output destinations, supporting file paths, file-like objects, or returning content as a file-like object when no destination is provided.
- Parameters:
content (str or bytes) – Content to write. Can be text (str) or binary (bytes) data.
output (str, Path, IO[bytes], IO[str], or None) – Output destination. Can be: - None: Returns content as StringIO (for str) or BytesIO (for bytes) - str or Path: Writes content to file at that path - IO[bytes]: Writes content to binary file-like object - IO[str]: Writes content to text file-like object
- Returns:
If output is None: Returns StringIO (for str content) or BytesIO (for bytes content)
Otherwise: Returns None after writing to the destination
- Return type:
StringIO, BytesIO, or None
- Raises:
TypeError – If output type is not supported or content type doesn’t match file mode
Examples
- Return as file-like object:
>>> content = "Hello, world!" >>> result = write_content(content, None) >>> isinstance(result, StringIO) True >>> result.read() 'Hello, world!'
- Write to file path:
>>> write_content("test content", "output.txt") >>> Path("output.txt").read_text() 'test content'
- Write to file-like object:
>>> from io import BytesIO >>> buffer = BytesIO() >>> write_content(b"binary data", buffer) >>> buffer.getvalue() b'binary data'