Skip to content

File I/O

file_io

Provide small generic text-file I/O helpers.

read_text

read_text(path: Path, *, encoding: str = 'utf-8') -> str

Read a text file.

Parameters:

Name Type Description Default
path Path

File to read.

required
encoding str

Text encoding.

'utf-8'

Returns:

Type Description
str

File contents.

Raises:

Type Description
OSError

If the file cannot be read.

Source code in hotstring\file_io.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def read_text(path: Path, *, encoding: str = "utf-8") -> str:
    """Read a text file.

    Args:
        path:
            File to read.
        encoding:
            Text encoding.

    Returns:
        File contents.

    Raises:
        OSError:
            If the file cannot be read.
    """
    return path.read_text(encoding=encoding)

write_text

write_text(
    path: Path,
    text: str,
    *,
    append: bool = False,
    encoding: str = "utf-8",
    create_parents: bool = True,
) -> None

Write or append text to a file.

Parameters:

Name Type Description Default
path Path

Destination file.

required
text str

Text to write.

required
append bool

Append instead of replacing the current contents.

False
encoding str

Text encoding.

'utf-8'
create_parents bool

Create missing parent directories before writing.

True

Raises:

Type Description
OSError

If the destination cannot be written.

Source code in hotstring\file_io.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def write_text(
    path: Path,
    text: str,
    *,
    append: bool = False,
    encoding: str = "utf-8",
    create_parents: bool = True,
) -> None:
    """Write or append text to a file.

    Args:
        path:
            Destination file.
        text:
            Text to write.
        append:
            Append instead of replacing the current contents.
        encoding:
            Text encoding.
        create_parents:
            Create missing parent directories before writing.

    Raises:
        OSError:
            If the destination cannot be written.
    """
    if create_parents:
        path.parent.mkdir(parents=True, exist_ok=True)

    mode = "a" if append else "w"
    with path.open(mode, encoding=encoding, newline="") as stream:
        stream.write(text)