Skip to content

filehandlers API Reference

The main module.

AbstractFile

A file in instance form.

__abs__(self) special

Override of abs() and __abs__.

Provides the absolute path to the file.

Returns:

Type Description
str

The absolute path to the file.

Source code in filehandlers/__init__.py
33
34
35
36
37
38
39
40
41
42
def __abs__(self) -> str:
    """
    Override of `abs()` and `__abs__`.

    Provides the absolute path to the file.

    Returns:
        The absolute path to the file.
    """
    return os.path.abspath(self.name)

__init__(self, name) special

Creates the class.

Parameters:

Name Type Description Default
name str

The file name.

required

Returns:

Type Description
None

Nothing.

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

    Args:
        name: The file name.

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

__str__(self) special

Override of str() and __str__.

Returns:

Type Description
str

The name of the file.

Source code in filehandlers/__init__.py
24
25
26
27
28
29
30
31
def __str__(self) -> str:
    """
    Override of `str()` and `__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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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

parent_directory(self)

Get the parent directory of this file's path.

Returns:

Type Description
str

The absolute path to the parent directory.

Source code in filehandlers/__init__.py
79
80
81
82
83
84
85
86
def parent_directory(self) -> str:
    """
    Get the parent directory of this file's path.

    Returns:
        The absolute path to the parent directory.
    """
    return os.path.abspath(os.path.dirname(self.name))

touch(self)

Create the file if it doesn't already exist.

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
None

Nothing.

Exceptions:

Type Description
PermissionError

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

Source code in filehandlers/__init__.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def touch(self) -> None:
    """
    Create the file if it doesn't already exist.

    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.
    """
    open(str(self), mode="a").close()

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
None

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) -> None:
    """
    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._linked_abstractfile = 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
None

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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def clear_file(self) -> None:
    """
    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
bool

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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def delete(self) -> bool:
    """
    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._linked_abstractfile

get_file_contents_singlestring(self)

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

Warning

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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def get_file_contents_singlestring(self) -> str:
    """
    Get the file's contents, but as one multi-line string.

    !!! warning
        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.
    """
    o = open(str(self.get_file()), mode="r")
    string = o.read()
    o.close()
    return string

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
247
248
249
250
251
252
253
254
255
256
257
258
259
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
None

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) -> None:
    """
    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()

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
None

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) -> None:
    """
    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 = open(str(self.get_file()), mode="w")
    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: