Skip to content

Work with file system

parse_path(path)

Parse a string literal or a Path object into a Path object.

In the latter case, the function does not do anything but return the given Path object directly.

I also use this function to directly parse file and directory input strings passed in from command line.

Examples:

>>> from tinyscibio import parse_path
>>> p = "/home/user1/project"
>>> parse_path(p)
Path("/home/user1/project")
>>> from pathlib import Path
>>> from tinyscibio import parse_path
>>> p_obj = Path("/home/user1/project")
>>> parse_path(p_obj)
Path("/home/user1/project")
>>> from tinyscibio import parse_path
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
        "--bam",
        metavar="FILE",
        type=parse_path,
        help="Specify the path to the BAM file"
    )
>>> args = parser.parse_args()
>>> isinstance(args.bam, Path)
true

Parameters:

Name Type Description Default
path _PathLike

Either a string literal or a Path object.

required

Returns:

Type Description
Path

A Path object.

Raises:

Type Description
ValueError

When input path parameter is an empty string

make_dir(path, parents=False, exist_ok=False)

Create a directory at the specified location.

Examples:

>>> from tinyscibio import make_dir
>>> p = "/home/user1/projects"
>>> new_p = make_dir(p, parents=True, exist_ok=True)
>>> new_p
Path("/home/user1/projects")

Parameters:

Name Type Description Default
path _PathLike

Either a string literal or a Path object.

required
parents bool

Whether or not creating parental folders leading to the given path when not existed.

False
exist_ok bool

Whether or not allowing the directory trying to be created already existed.

False

Returns:

Type Description
Path

A Path object pointing to the newly created directory.

Raises:

Type Description
FileNotFoundError

When parental folders leading to the given path does not exists, and parents parameter is False

FileExistsError

When trying to create a directory that already existed, and exist_ok parameter is False. Or when trying to create a directory at the given location leading to a file.

get_parent_dir(path, level=0)

Get parent directory at the specified level for a given path.

Setting a level=0 means return the given path.

Examples:

>>> from tinyscibio import get_parent_dir
>>> p = "/home/user1/projects"
>>> get_parent_dir(p, level=1)
Path("/home/user1/")

Parameters:

Name Type Description Default
path _PathLike

Either a string literal or a Path object.

required
level int

Num of levels to walk back along a givne path

0

Returns:

Type Description
Path

A Path object.

Raises:

Type Description
ValueError

When the value of level is negative or larger than the number of parent folders in the given path