💾 io#
This module provides utilities for file management.
json_dump(): Writes the provided data to a JSON file with a specified indentation depth.json_load(): Load a JSON file from the given pathcsv_dump(): Writes data to a CSV file with customizable optionscsv_load(): Load a CSV file from the given pathget_root_path(): Get the absolute path of the directoryrelative_path(): Get the relative path of a file relative to a given directorysuper_copy(): Copy a file (or a folder) from the source to the destination (always create the directory)super_open(): Open a file with the given mode, creating the directory if it doesn’t exist (only if writing)replace_tilde(): Replace the “~” by the user’s home directoryclean_path(): Clean the path by replacing backslashes with forward slashes and simplifying the pathcopytree_with_progress(): Copy a directory tree with a colored progress barredirect_folder(): Move a folder and create a junction/symlink at the original locationsafe_close(): Safely close a file descriptor or file object after flushing, ignoring any exceptions
import stouputils as stp
config = {"model": "resnet50", "layers": [64, 128, 256], "optimizer": {"name": "adam", "lr": 0.001}}
# Write the dictionary to a JSON file, creating the configs folder on the way
stp.json_dump(config, "configs/run.json")
stp.info("Content of configs/run.json:")
print(stp.read_file("configs/run.json"))
# Read it back
stp.info("Same data back:", stp.json_load("configs/run.json") == config)
# Copy it, creating the destination folders on the way
stp.info("Copied to", stp.super_copy("configs/run.json", "archive/2026/run.json"))
# Simplify a path
stp.info("Cleaned:", stp.clean_path("archive/2026/../2026/./run.json"))
csv#
- csv_dump(
- data: Any,
- file: IO[Any] | str | None = None,
- delimiter: str = ',',
- has_header: bool = True,
- index: bool = False,
- *args: Any,
- **kwargs: Any,
Writes data to a CSV file with customizable options and returns the CSV content as a string.
- Parameters:
data – The data to write, either a list of lists, list of dicts, pandas DataFrame, or Polars DataFrame
file – The file object or path to dump the data to
delimiter – The delimiter to use (default: ‘,’)
has_header – Whether to include headers (default: True, applies to dict and DataFrame data)
index – Whether to include the index (default: False, only applies to pandas DataFrame)
*args – Additional positional arguments to pass to the underlying CSV writer or DataFrame method
**kwargs – Additional keyword arguments to pass to the underlying CSV writer or DataFrame method
- Returns:
The CSV content as a string
>>> csv_dump([["a", "b", "c"], [1, 2, 3], [4, 5, 6]]) 'a,b,c\r\n1,2,3\r\n4,5,6\r\n'
>>> csv_dump([{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]) 'name,age\r\nAlice,30\r\nBob,25\r\n'
- csv_text(
- data: Any,
- delimiter: str,
- has_header: bool,
- index: bool,
- args: tuple[Any, ...],
- kwargs: dict[str, Any],
The CSV text of a Polars or pandas DataFrame, or of a list of dicts or of lists, as
csv_dump()writes it.- Parameters:
args – Positional arguments for the underlying writer.
kwargs – Keyword arguments for the underlying writer, which must not repeat the ones built from the other parameters.
- csv_load(
- file_path: str,
- delimiter: str = ',',
- has_header: bool = True,
- as_dict: bool = False,
- as_dataframe: bool = False,
- use_polars: bool = False,
- *args: Any,
- **kwargs: Any,
Load a CSV file from the given path
- Parameters:
file_path – The path to the CSV file
delimiter – The delimiter used in the CSV (default: ‘,’)
has_header – Whether the CSV has a header row (default: True)
as_dict – Whether to return data as list of dicts (default: False)
as_dataframe – Whether to return data as a DataFrame (default: False)
use_polars – Whether to use Polars instead of pandas for DataFrame (default: False, requires polars)
*args – Additional positional arguments to pass to the underlying CSV reader or DataFrame method
**kwargs – Additional keyword arguments to pass to the underlying CSV reader or DataFrame method
- Returns:
The content of the CSV file
> Assuming "test.csv" contains: a,b,c\n1,2,3\n4,5,6 > csv_load("test.csv") [['1', '2', '3'], ['4', '5', '6']] > csv_load("test.csv", as_dict=True) [{'a': '1', 'b': '2', 'c': '3'}, {'a': '4', 'b': '5', 'c': '6'}] > csv_load("test.csv", as_dataframe=True) a b c 0 1 2 3 1 4 5 6
> csv_load("test.csv", as_dataframe=True, use_polars=True) shape: (2, 3) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 2 ┆ 3 │ │ 4 ┆ 5 ┆ 6 │ └─────┴─────┴─────┘
json#
- json_dump(
- data: Any,
- file: IO[Any] | str | Path | None = None,
- max_level: int | None = 2,
- indent: str | int = '\t',
- suffix: str = '\n',
- ensure_ascii: bool = False,
Writes the provided data to a JSON file with a specified indentation depth. For instance, setting max_level to 2 will limit the indentation to 2 levels.
- Parameters:
data – The data to dump (usually a dict or a list)
file – The file object or path to dump the data to
max_level – The depth of indentation to stop at (-1 for infinite), None will default to 2
indent – The indentation character (default: ‘t’)
suffix – The suffix to add at the end of the string (default: ‘n’)
ensure_ascii – Whether to escape non-ASCII characters (default: False)
- Returns:
The content of the file in every case
>>> json_dump({"a": [[1,2,3]], "b": 2}, max_level = 0) '{"a": [[1,2,3]],"b": 2}\n' >>> json_dump({"a": [[1,2,3]], "b": 2}, max_level = 1) '{\n\t"a": [[1,2,3]],\n\t"b": 2\n}\n' >>> json_dump({"a": [[1,2,3]], "b": 2}, max_level = 2) '{\n\t"a": [\n\t\t[1,2,3]\n\t],\n\t"b": 2\n}\n' >>> json_dump({"a": [[1,2,3]], "b": 2}, max_level = 3) '{\n\t"a": [\n\t\t[\n\t\t\t1,\n\t\t\t2,\n\t\t\t3\n\t\t]\n\t],\n\t"b": 2\n}\n' >>> json_dump({"éà": "üñ"}, ensure_ascii = True, max_level = 0) '{"\\u00e9\\u00e0": "\\u00fc\\u00f1"}\n' >>> json_dump({"éà": "üñ"}, ensure_ascii = False, max_level = 0) '{"éà": "üñ"}\n'
path#
- get_root_path(
- relative_path: str | Path,
- go_up: int = 0,
Get the absolute path of the directory. Usually used to get the root path of the project using the __file__ variable.
- Parameters:
relative_path – The path to get the absolute directory path from
go_up – Number of parent directories to go up (default: 0)
- Returns:
The absolute path of the directory
> get_root_path(__file__) 'C:/Users/Alexandre-PC/AppData/Local/Programs/Python/Python310/lib/site-packages/stouputils' > get_root_path(__file__, 3) 'C:/Users/Alexandre-PC/AppData/Local/Programs/Python/Python310'
- relative_path(
- file_path: str | Path,
- relative_to: str | Path = '',
Get the relative path of a file relative to a given directory.
- Parameters:
file_path – The path to get the relative path from
relative_to – The path to get the relative path to (default: current working directory -> os.getcwd())
- Returns:
The relative path of the file
>>> relative_path("D:/some/random/path/stouputils/io.py", "D:\\some") 'random/path/stouputils/io.py' >>> relative_path("D:/some/random/path/stouputils/io.py", "D:\\some\\") 'random/path/stouputils/io.py'
- super_copy(
- src: str | Path,
- dst: str | Path,
- create_dir: bool = True,
- symlink: bool = False,
Copy a file (or a folder) from the source to the destination
- Parameters:
src – The source path
dst – The destination path
create_dir – Whether to create the directory if it doesn’t exist (default: True)
symlink – Whether to create a symlink instead of copying (Linux only)
- Returns:
The destination path
- super_open(
- file_path: str | Path,
- mode: str,
- encoding: str = 'utf-8',
Open a file with the given mode, creating the directory if it doesn’t exist (only if writing)
- Parameters:
file_path – The path to the file
mode – The mode to open the file with, ex: “w”, “r”, “a”, “wb”, “rb”, “ab”
encoding – The encoding to use when opening the file (default: “utf-8”)
- Returns:
The file object, ready to be used
- read_file(
- file_path: str | Path,
- encoding: str = 'utf-8',
Read the content of a file and return it as a string
- Parameters:
file_path – The path to the file
encoding – The encoding to use when opening the file (default: “utf-8”)
- Returns:
The content of the file
- replace_tilde(path: str | Path) str[source]#
Replace the “~” by the user’s home directory
- Parameters:
path – The path to replace the “~” by the user’s home directory
- Returns:
The path with the “~” replaced by the user’s home directory
> replace_tilde("~/Documents/test.txt") '/home/user/Documents/test.txt'
- clean_path(
- file_path: str | Path,
- trailing_slash: bool = True,
Clean the path by replacing backslashes with forward slashes and simplifying the path
- Parameters:
file_path – The path to clean
trailing_slash – Whether to keep the trailing slash, ex: “test/” -> “test/”
- Returns:
The cleaned path
>>> clean_path("C:\\Users\\Stoupy\\Documents\\test.txt") 'C:/Users/Stoupy/Documents/test.txt' >>> clean_path("Some Folder////") 'Some Folder/' >>> clean_path("test/uwu/1/../../") 'test/' >>> clean_path("some/./folder/../") 'some/' >>> clean_path("folder1/folder2/../../folder3") 'folder3' >>> clean_path("./test/./folder/") 'test/folder/' >>> clean_path("C:/folder1\\folder2") 'C:/folder1/folder2' >>> clean_path("sftp://example.com/./folder/../file.txt") 'sftp://example.com/file.txt'
redirect#
- LINK_TYPE_ALIASES: dict[str, str] = {'hard': 'junction', 'hardlink': 'junction', 'j': 'junction', 'junction': 'junction', 's': 'symlink', 'sym': 'symlink', 'symbolic': 'symlink', 'symlink': 'symlink'}[source]#
Accepted spellings of a
link_type, by the kind of link each one makes.
- is_junction(path: str) bool[source]#
Check if a path is a junction point (Windows) or a symlink (any OS).
- Parameters:
path – The path to check
- Returns:
True if the path is a junction or symlink
- create_junction(source: str, target: str) None[source]#
Create a directory junction on Windows pointing source -> target. Uses ‘mklink /J’ command.
- Parameters:
source – The junction path to create (with forward slashes, will be converted)
target – The target directory the junction points to
- create_bind_mount(source: str, target: str) None[source]#
Create a bind mount on Linux pointing source -> target. Uses
mount --bindcommand (requires root/sudo).Note
Bind mounts do not persist across reboots unless an entry is added to
/etc/fstab. To make it persistent, add this line to/etc/fstab:/absolute/path/to/target /absolute/path/to/source none bind 0 0
- Parameters:
source – The mount point path to create (must exist as an empty directory)
target – The target directory to bind
- Raises:
OSError – If the bind mount command fails
- copytree_with_progress(
- source: str,
- destination: str,
- desc: str = 'Copying',
Copy a directory tree from source to destination with a colored progress bar.
Uses
progress_bar()to display progress while copying each file. Directory structure is created automatically. Existing files at the destination are overwritten.- Parameters:
source – Path to the source directory to copy
destination – Path to the destination directory
desc – Description for the progress bar (default:
"Copying")
- Returns:
The destination path
- Raises:
NotADirectoryError – If source is not a directory
import stouputils as stp # Create a folder with 3000 small files for index in range(3000): stp.super_open(f"photos/2026/photo_{index}.txt", "w").write("pixels") # Copy it with a progress bar, creating the destination folders on the way stp.copytree_with_progress("photos", "backup/photos")
- redirect_folder(
- source: str,
- destination: str,
- link_type: str | None = None,
Move a folder from source to destination and create a link at the original source location.
If the source is already a symlink or junction, the operation is skipped. If the destination path ends with
/, the source folder’s basename is appended automatically.- Link types:
"junction"(or"hardlink"): Uses an NTFS junction on Windows,or a bind mount (
mount --bind, requires sudo) on Linux. Falls back to symlink if junction/bind mount creation fails.
"symlink": Uses a symbolic link (may require elevated privileges on Windows).None: Prompts the user interactively.
- Parameters:
source – Path to the existing folder to redirect
destination – Path where the folder contents will be moved to
link_type –
"hardlink"/"junction","symlink", or None to ask
- Returns:
The final destination path
import os import stouputils as stp # A game folder on the main disk for index in range(500): stp.super_open(f"games/MyGame/level_{index}.bin", "w").write("level data") # Move it to another disk and leave a link at the old place, so nothing else has to change stp.redirect_folder("games/MyGame", "other_disk/games/", link_type="symlink") stp.info("games/MyGame now points to", os.readlink("games/MyGame"))
- confirm_or_abort(question: str) bool[source]#
Ask a yes/no question on stdin, no being the default, and report the abort when the answer is no.
- normalize_link_type(link_type: str) str[source]#
The kind of link an accepted spelling of
link_typemakes,"junction"or"symlink".- Raises:
ValueError – If the spelling is not one of
LINK_TYPE_ALIASES.
>>> normalize_link_type(" Hard ") 'junction'
- ask_link_type(source: str, destination: str) str[source]#
Ask on stdin how
sourceshould be linked todestination.- Returns:
"junction"or"symlink".