Skip to content

filehandlers API Reference

The main module.

AbstractFile

A file in instance form.

__init__(self, name) special

Creates the class.

Parameters:

Name Type Description Default
name str

The file name.

required

Returns:

Type Description

Nothing.

Source code in filehandlers/__init__.py
13
14
15
16
17
18
19
20
21
22
23
def __init__(self, name: str):
    """
    Creates the class.

    Args:
        name: The file name.

    Returns:
        Nothing.
    """
    self.name = name

__str__(self) special

Override of __str__.

Returns:

Type Description
str

The name of the file.

Source code in filehandlers/__init__.py
25
26
27
28
29
30
31
32
def __str__(self) -> str:
    """
    Override of `__str__`.

    Returns:
        The name of the file.
    """
    return self.name

exists(self, touch_if_false=False)

Get if this file exists or not (boolean value).

Returns:

Type Description
bool

If the file exists.

Parameters:

Name Type Description Default
touch_if_false Optional[bool]

If the file should be created if it doesn't exist.

False

Exceptions:

Type Description
PermissionError

If you don't have the required permissions to access the file.

Source code in filehandlers/__init__.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def exists(self, touch_if_false: Optional[bool] = False) -> bool:
    """
    Get if this file exists or not (boolean value).

    Returns:
        If the file exists.

    Arguments:
        touch_if_false: If the file should be created if it doesn't exist.

    Raises:
        PermissionError: If you don't have the required permissions to access the file.
    """
    e = False
    if os.path.exists(self.name):
        e = True
        if touch_if_false:
            self.touch()
    return e

touch(self)

Create the file if it doesn't already exist.

Important

This is the only method that actually changes/interacts with the file inside the AbstractFile class (other then wrap and exists).

In case you are wondering, the name for this function comes from the Unix command touch, which creates a new file with the name as a parameter.

Returns:

Type Description

Nothing.

Exceptions:

Type Description
PermissionError

If you don't have needed permission to access the file.

Source code in filehandlers/__init__.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def touch(self):
    """
    Create the file if it doesn't already exist.

    !!! important
        This is the only method that actually changes/interacts with the file
        inside the AbstractFile class (other then
        [`wrap`](#filehandlers.AbstractFile.wrap) and
        [`exists`](#filehandlers.AbstractFile.exists)).

    In case you are wondering, the name for this function comes from the Unix command
    `touch`, which creates a new file with the name as a parameter.

    Returns:
        Nothing.

    Raises:
        PermissionError: If you don't have needed permission to access the file.
    """
    self.wrap().close()

wrap(self)

Wrap the file in a TextIOWrapper (part of the Python standard library, return type of open()).

Returns:

Type Description

The wrapper.

Exceptions:

Type Description
PermissionError

If you don't have needed permission to access the file.

Source code in filehandlers/__init__.py
34
35
36
37
38
39
40
41
42
43
44
45
def wrap(self):
    """
    Wrap the file in a `TextIOWrapper` (part of the Python standard library,
    return type of `open()`).

    Returns:
        The wrapper.

    Raises:
        PermissionError: If you don't have needed permission to access the file.
    """
    return open(str(self), mode="a")

FileManipulator

Class used for managing an assigned file.

__init__(self, abstract_file) special

Create class instance.

Parameters:

Name Type Description Default
abstract_file AbstractFile

The AbstractFile instance.

required

Returns:

Type Description

Nothing.

Exceptions:

Type Description
TypeError

If the argument isn't an AbstractFile.

Source code in filehandlers/__init__.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def __init__(self, abstract_file: AbstractFile):
    """
    Create class instance.

    Arguments:
        abstract_file: The AbstractFile instance.

    Returns:
        Nothing.

    Raises:
        TypeError: If the argument isn't an AbstractFile.
    """
    self.cache = []
    if type(abstract_file) == AbstractFile:
        self.theFile = abstract_file
    else:
        raise TypeError("Wrong type! Please pass AbstractFile or string")
    self.refresh()

clear_file(self)

Clear the file.

Warning: You will not be able to recover the old contents!

Returns:

Type Description

Nothing.

Exceptions:

Type Description
PermissionError

If you don't have needed permission to access the file.

FileNotFoundError

If the file doesn't exist.

Source code in filehandlers/__init__.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def clear_file(self):
    """
    Clear the file.

    Warning: You will not be able to recover the old contents!

    Returns:
        Nothing.

    Raises:
        PermissionError: If you don't have needed permission to access the file.
        FileNotFoundError: If the file doesn't exist.
    """
    open(str(self.get_file()), mode="w").close()

delete(self)

Delete the file if it exists.

Returns:

Type Description

If it got deleted or not (can be ignored by just calling the method).

Exceptions:

Type Description
PermissionError

If you don't have needed permission to access the file.

Source code in filehandlers/__init__.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def delete(self):
    """
    Delete the file if it exists.

    Returns:
        If it got deleted or not (can be ignored by just calling the method).

    Raises:
        PermissionError: If you don't have needed permission to access the file.
    """
    if self.get_file().exists():
        os.remove(str(self.get_file()))
        return True
    return False

get_cache(self)

Get the cache.

The cache will be a list of the file's lines at the time of the last refresh.

Refreshes are called when this class is created, or when manually triggered by [refresh].

Returns:

Type Description
List[str]

The cache.

Source code in filehandlers/__init__.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def get_cache(self) -> List[str]:
    """
    Get the cache.

    The cache will be a list of the file's lines at the time of the
    last refresh.

    Refreshes are called when this class is created,
    or when manually triggered by [refresh].

    Returns:
        The cache.
    """
    return self.cache

get_file(self)

Get the AbstractFile instance.

Returns:

Type Description
AbstractFile

The AbstractFile instance.

Source code in filehandlers/__init__.py
115
116
117
118
119
120
121
122
def get_file(self) -> AbstractFile:
    """
    Get the AbstractFile instance.

    Returns:
        The AbstractFile instance.
    """
    return self.theFile

get_file_contents_singlestring(self)

Get the file's contents, but as one multi-line string.

Important: This function does not use the cache.

Returns:

Type Description
str

The file's contents.

Exceptions:

Type Description
PermissionError

If you don't have needed permission to access the file.

FileNotFoundError

If the file doesn't exist.

Source code in filehandlers/__init__.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def get_file_contents_singlestring(self) -> str:
    """
    Get the file's contents, but as one multi-line string.

    Important: This function does not use the cache.

    Returns:
        The file's contents.

    Raises:
        PermissionError: If you don't have needed permission to access the file.
        FileNotFoundError: If the file doesn't exist.
    """
    return open(str(self.get_file()), mode="r").read()

get_file_name(self)

Get the file's name.

Returns:

Type Description
str

The file's name.

Source code in filehandlers/__init__.py
124
125
126
127
128
129
130
131
def get_file_name(self) -> str:
    """
    Get the file's name.

    Returns:
        The file's name.
    """
    return str(self.get_file())

load_from_json(self)

Loads the file, and returns the dictionary containing the data.

Returns:

Type Description
Dict[str, Any]

The dictionary with the data.

Exceptions:

Type Description
JSONDecodeError

If it isn't valid JSON.

PermissionError

If you don't have needed permission to access the file.

FileNotFoundError

If the file doesn't exist.

Source code in filehandlers/__init__.py
252
253
254
255
256
257
258
259
260
261
262
263
264
def load_from_json(self) -> Dict[str, Any]:
    """
    Loads the file, and returns the dictionary containing the data.

    Returns:
        The dictionary with the data.

    Raises:
        JSONDecodeError: If it isn't valid JSON.
        PermissionError: If you don't have needed permission to access the file.
        FileNotFoundError: If the file doesn't exist.
    """
    return loads(self.get_file_contents_singlestring())

refresh(self, slim=False)

Update the cache.

Parameters:

Name Type Description Default
slim Optional[bool]

If empty lines should be removed.

False

Returns:

Type Description

Nothing.

Exceptions:

Type Description
PermissionError

If you don't have needed permission to access the file.

Source code in filehandlers/__init__.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def refresh(self, slim: Optional[bool] = False):
    """
    Update the cache.

    Arguments:
        slim: If empty lines should be removed.

    Returns:
        Nothing.

    Raises:
        PermissionError: If you don't have needed permission to access the file.
    """
    if not self.get_file().exists():
        # file doesn't exist, exit early
        return

    with open(self.get_file_name(), mode="r") as fh:
        self.cache = fh.readlines()
        # strip newlines
        for h, g in enumerate(self.cache):
            if slim and self.cache[h] == "":
                self.cache.pop(h)
            else:
                self.cache[h] = self.cache[h].replace("\n", "")
        fh.close()

wrap_file(self)

Shortcut for self.get_file().wrap().

Returns:

Type Description
TextIOWrapper

The wrapped file.

Source code in filehandlers/__init__.py
198
199
200
201
202
203
204
205
def wrap_file(self) -> io.TextIOWrapper:
    """
    Shortcut for `self.get_file().wrap()`.

    Returns:
        The wrapped file.
    """
    return self.theFile.wrap()

write_to_file(self, string)

Write to the file.

Types

Please ensure that what you are writing to the file is a string.

Parameters:

Name Type Description Default
string str

What to write to the file.

required

Exceptions:

Type Description
PermissionError

If you don't have needed permission to access the file.

TypeError

If you pass an unsupported type to be written.

FileNotFoundError

If the file doesn't exist.

Returns:

Type Description

Nothing.

Source code in filehandlers/__init__.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def write_to_file(self, string: str):
    """
    Write to the file.

    !!! warning "Types"
        Please ensure that what you are writing to the file
        is a string.

    Arguments:
        string: What to write to the file.

    Raises:
        PermissionError: If you don't have needed permission to access the file.
        TypeError: If you pass an unsupported type to be written.
        FileNotFoundError: If the file doesn't exist.

    Returns:
        Nothing.
    """
    e = self.wrap_file()
    e.write(string)
    e.close()

OpenModes

Enum for the different options you can pass to the keyword argument mode in Python's open function.

It can be used like this:

from filehandlers import OpenModes
open("myfile.txt", mode=OpenModes.READ.value)

This can help so you don't need to remember all the different mode options.

Using WRITE

For the write option, the file will be cleared and then written to. To avoid this, use append instead!

Binary mode vs Text mode

Text mode should be used when writing text files (whether using plain text or a text-based format like TXT), while binary mode must be used when writing non-text files like images.

APPEND class-attribute

Create the file - raises error if file exists.

BINARY class-attribute

This will open a file for reading and writing (updating).

CLEAR class-attribute

Append to the end of the file (also gives read!).

CREATE class-attribute

Create the file and ready it to be written to.

CREATE_AND_WRITE class-attribute

The default option for the built-in open function.

READ class-attribute

Read only access to the file (binary enabled).

READ_BINARY class-attribute

Write only access to the file - see warning above.

TEXT class-attribute

Open in binary mode.

WRITE class-attribute

Write only access to the file - see warning above (binary enabled).

WRITE_BINARY class-attribute

Clear the file.


Last update: