cvtk.utils

This module provides utility functions for configuration management, JSON handling, code transformation, and other common operations used throughout the cvtk package.

API Reference

class cvtk.utils.Path(*args, **kwargs)[source]

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

classmethod cwd()[source]

Return a new path pointing to the current working directory (as returned by os.getcwd()).

classmethod home()[source]

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

samefile(other_path)[source]

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

iterdir()[source]

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

glob(pattern)[source]

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

rglob(pattern)[source]

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

absolute()[source]

Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.

Use resolve() to get the canonical path to a file.

resolve(strict=False)[source]

Make the path absolute, resolving all symlinks on the way and also normalizing it.

stat(*, follow_symlinks=True)[source]

Return the result of the stat() system call on this path, like os.stat() does.

owner()[source]

Return the login name of the file owner.

group()[source]

Return the group name of the file gid.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[source]

Open the file pointed by this path and return a file object, as the built-in open() function does.

read_bytes()[source]

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)[source]

Open the file in text mode, read it, and close the file.

write_bytes(data)[source]

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)[source]

Open the file in text mode, write to it, and close the file.

readlink()[source]

Return the path to which the symbolic link points.

touch(mode=438, exist_ok=True)[source]

Create this file with the given access mode, if it doesn’t exist.

mkdir(mode=511, parents=False, exist_ok=False)[source]

Create a new directory at this given path.

chmod(mode, *, follow_symlinks=True)[source]

Change the permissions of the path, like os.chmod().

lchmod(mode)[source]

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

unlink(missing_ok=False)[source]

Remove this file or link. If the path is a directory, use rmdir() instead.

rmdir()[source]

Remove this directory. The directory must be empty.

lstat()[source]

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

rename(target)[source]

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)[source]

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

symlink_to(target, target_is_directory=False)[source]

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

hardlink_to(target)[source]

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

link_to(target)[source]

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

exists()[source]

Whether this path exists.

is_dir()[source]

Whether this path is a directory.

is_file()[source]

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()[source]

Check if this path is a POSIX mount point

is_symlink()[source]

Whether this path is a symbolic link.

is_block_device()[source]

Whether this path is a block device.

is_char_device()[source]

Whether this path is a character device.

is_fifo()[source]

Whether this path is a FIFO.

is_socket()[source]

Whether this path is a socket.

expanduser()[source]

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

class cvtk.utils.JsonComplexEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

JSON encoder that handles numpy data types.

Extends json.JSONEncoder to serialize numpy integers, floats, arrays, and NaN values. Automatically converts these types to native Python types for JSON serialization.

Examples

>>> import numpy as np
>>> data = {'arr': np.array([1, 2, 3]), 'val': np.int64(42)}
>>> json.dumps(data, cls=JsonComplexEncoder)
'{"arr": [1, 2, 3], "val": 42}'
default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
cvtk.utils.as_list(x)[source]

Convert input to a list.

Converts strings and dicts to single-element lists, lists/tuples to lists.

Parameters:

x (str|dict|list|tuple) – Input to convert.

Returns:

Input converted to list format.

Return type:

list

Examples

>>> as_list('hello')
['hello']
>>> as_list(['a', 'b'])
['a', 'b']
>>> as_list(('x', 'y'))
['x', 'y']
cvtk.utils.save_json(data, output, indent=None, ensure_ascii=False)[source]

Save data to a JSON file with support for numpy types.

Serializes and writes data to a JSON file using JsonComplexEncoder to handle numpy data types.

Parameters:
  • data – Data to serialize (dict, list, or any JSON-serializable type with numpy support).

  • output (str) – File path where JSON will be saved.

  • indent (int|None) – Indentation level for pretty-printing.

  • ensure_ascii (bool) – If False, allows non-ASCII characters (e.g., Unicode). Default is False.

Examples

>>> data = {'values': [1, 2, 3], 'arr': np.array([4, 5, 6])}
>>> save_json(data, 'output.json')
>>> save_json(data, 'output_compact.json', indent=None)