-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.py
190 lines (150 loc) · 5.16 KB
/
helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python3
"""[summary]"""
## IMPORTS ##
# External
import json
import matplotlib.pyplot as plt
import os
import pickle
import zipfile
from typing import Any, List
from zipfile import ZipFile
def json_load(path: str) -> Any:
"""Loads the given JSON file and returns it as json_data (a list
or a dictionary).
Arguments
----------
* path: str ~ The path of the JSON file
"""
with open(path) as f:
json_data = json.load(f)
return json_data
def json_write(path: str, json_data: Any) -> None:
"""Writes a JSON file at the given path with the given dictionary as content.
Arguments
----------
* path: str ~ The path of the JSON file that shall be written
* json_data: Any ~ The dictionary or list which shalll be the content of
the created JSON file
"""
json_output = json.dumps(json_data, indent=4)
with open(path, "w", encoding="utf-8") as f:
f.write(json_output)
def json_zip_load(path: str) -> Any:
"""Loads the given zipped JSON file and returns it as json_data (a list
or a dictionary).
Arguments
----------
* path: str ~ The path of the JSON file without ".zip" at the end
"""
old_wd = os.getcwd()
folder = os.path.dirname(path)
filename = os.path.basename(path)
os.chdir(folder)
with ZipFile(filename+".zip", 'r') as zip:
zip.extractall()
with open(filename) as f:
json_data = json.load(f)
os.remove(filename)
os.chdir(old_wd)
return json_data
def json_zip_write(path: str, json_data: Any, zip_method: int=zipfile.ZIP_LZMA) -> None:
"""Writes a zipped JSON file at the given path with the given dictionary as content.
Arguments
----------
* path: str ~ The path of the JSON file that shall be written without ".zip" at the end
* json_data: Any ~ The dictionary or list which shalll be the content of
the created JSON file
"""
json_output = json.dumps(json_data, indent=4)
with open(path, "w", encoding="utf-8") as f:
f.write(json_output)
old_wd = os.getcwd()
folder = os.path.dirname(path)
filename = os.path.basename(path)
os.chdir(folder)
with ZipFile(filename+".zip", 'w', zip_method) as zip:
zip.write(filename)
os.chdir(old_wd)
os.remove(path)
def ensure_folder_existence(folder: str) -> None:
"""Checks if the given folder exists. If not, the folder is created.
Argument
----------
* folder: str ~ The folder whose existence shall be enforced.
"""
if os.path.isdir(folder):
return
os.makedirs(folder)
def ensure_json_existence(path: str) -> None:
if os.path.isfile(path):
return
with open(path, "w") as f:
f.write("{}")
def get_files(path: str) -> List[str]:
"""Returns the names of the files in the given folder as a list of strings.
Arguments
----------
* path: str ~ The path to the folder of which the file names shall be returned
"""
files: List[str] = []
for (_, _, filenames) in os.walk(path):
files.extend(filenames)
return files
def pickle_load(path: str) -> Any:
"""Returns the value of the given pickle file.
Arguments
----------
* path: str ~ The path to the pickle file.
"""
pickle_file = open(path, 'rb')
pickled_object = pickle.load(pickle_file)
pickle_file.close()
return pickled_object
def pickle_write(path: str, pickled_object: Any) -> None:
"""Writes the given object as pickled file with the given path
Arguments
----------
* path: str ~ The path of the pickled file that shall be created
* pickled_object: Any ~ The object which shall be saved in the pickle file
"""
pickle_file = open(path, 'wb')
pickle.dump(pickled_object, pickle_file)
pickle_file.close()
def standardize_folder(folder: str) -> str:
"""Returns for the given folder path is returned in a more standardized way.
I.e., folder paths with potential \\ are replaced with /. In addition, if
a path does not end with / will get an added /.
Argument
----------
* folder: str ~ The folder path that shall be standardized.
"""
# Standardize for \ or / as path separator character.
folder = folder.replace("\\", "/")
# If the last character is not a path separator, it is
# added so that all standardized folder path strings
# contain it.
if folder[-1] != "/":
folder += "/"
return folder
def save_xy_point_plot(path: str, xs: List[float], ys: List[float], title: str, xlabel: str, ylabel: str,
style: str="bo", clear_previous_figure: bool=True):
"""[summary]
Args:
path (str): [description]
xs (List[float]): [description]
ys (List[float]): [description]
title (str): [description]
xlabel (str): [description]
ylabel (str): [description]
style (str, optional): [description]. Defaults to "bo".
clear_previous_figure (bool, optional): [description]. Defaults to True.
"""
if clear_previous_figure:
plt.clf()
plt.plot(xs, ys, style)
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if path != "":
plt.savefig(path)