-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_handler.py
More file actions
292 lines (248 loc) · 9.54 KB
/
file_handler.py
File metadata and controls
292 lines (248 loc) · 9.54 KB
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import json
import subprocess
import sys
import csv
import os
import xml.etree.cElementTree as ET
from PyQt5.QtWidgets import QApplication, QFileDialog
from tkinter import messagebox
class FileHandler:
"""
Handle saving and retrieving of JSON objects/files
"""
@staticmethod
def save_project(project_info):
"""
Saves project python dictionary into user-defined directory as a .JSON file.
Parameters:
project_info (dict()): Project dictionary
Returns:
0 if successful, else -1.
"""
# Get first key/value pair in the dictionary
project_name = list(project_info.items())[0][1]
# Loop directory prompt until success or cancel
while True:
try:
# Prompt user for path
path = FileHandler.prompt_dir()
# Create project directory and update path with new directory
path = FileHandler.create_dir(project_name, path)
# Create config.json file
FileHandler.create_file(path, ".json", project_info, "CONFIG")
# Update CURRENT_WORKING_PROJECT.JSON
FileHandler.update_current_project(path)
# Creating packet_data.json with preset Json dictionary
FileHandler.make_preset_json(path)
#Creating blacklist for user
FileHandler.make_blacklist(path)
#Creating decoded_data.json for user
FileHandler.make_decoded_data(path)
#Create Map for user
FileHandler.make_map(path)
return 0
# The user has tried to create an already existing directory
except FileExistsError:
messagebox.showerror(title="CAN Bus Visualizer", message="Folder Already Exists!")
except FileNotFoundError:
break
return -1
@staticmethod
def make_map(path):
newfile = open(path+"/map.json", "w")
newfile.close()
@staticmethod
def make_decoded_data(path):
newfile = open(path+"/decoded_data_json.json", "w")
newfile.close()
@staticmethod
def make_blacklist(path):
newfile = open(path+"/blacklist.txt", "w")
newfile.close()
@staticmethod
def update_current_project(path):
"""
Updates the Current_Working_Project.json with the new provided user path
Parameters:
path: the new folder path of the user
"""
# This code can NOT be substitued with get_curr_project()
# This code Reads the path of the c.w.p. json file
with open("Current_Working_Project.json", "r") as jsonFile:
data = json.load(jsonFile)
data["Project_path"] = path
# This code dumps the new path to the c.w.p. json file
with open("Current_Working_Project.json", "w") as jsonFile:
json.dump(data, jsonFile)
@staticmethod
def get_current_project():
with open("Current_Working_Project.json", "r") as jsonFile:
data = json.load(jsonFile)
return data["Project_path"]
@staticmethod
def make_preset_json(path):
"""
Makes and writes Json Dictionary for the file packet_data.json in the users directory
Parameters:
path: the folder path of the user
"""
# Create packet_data.json for user folder
with open(path+"/packet_data.json", "w") as jsonFile:
json_string = {
"packets": [
{
"timestamp": "-",
"id": "-",
"s": "-",
"dl": "-",
"channel": "-",
"annotate": "-"
}
]
}
json.dump(json_string, jsonFile)
@staticmethod
def export_to_csv(py_dict):
"""
Exports python dictionary into user-defined directory as a .CSV file.
Parameters:
py_dict (dict()): Python dictionary data
Returns:
0 if successful, else -1.
"""
# Get file information
file_info = FileHandler.prompt_file_save()
# If file saved
if file_info:
# Create CSV file
FileHandler.create_file(file_info[0], file_info[2], py_dict, file_name=file_info[1])
return 0
return -1
@staticmethod
def export(py_dict):
"""
Exports python dictionary into user-defined directory as a .XML file.
Parameters:
py_dict (dict()): Python dictionary data
Returns:
0 if successful, else -1.
"""
# Get file information
file_info = FileHandler.prompt_file_save()
# If file saved
if file_info:
# Create XML file
FileHandler.create_file(file_info[0], file_info[2], py_dict, file_name=file_info[1])
return 0
return -1
@staticmethod
def create_dicts():
py_dict = {}
path = FileHandler.get_current_project()
j_file = open(path+"/CONFIG.json", 'r')
# d_file = open(path+"/decoded_data_json.json", 'r')
# m_file = open(path+"/map.json", 'r')
# p_file = open(path+"/packet_data.json", 'r')
data_dict_j = json.loads(j_file.read())
# data_dict_d = json.loads(d_file.read())
# data_dict_m = json.loads(m_file.read())
# data_dict_p = json.loads(p_file.read())
py_dict["Project_Config"] = data_dict_j
# py_dict["Decoded"].append(data_dict_d)
# py_dict["Map"].append(data_dict_m)
# py_dict["Packet_Data"] = data_dict_p
return py_dict
@staticmethod
def create_file(path, file_type, file_contents, file_name="place_holder"):
"""
File creator
Parameters:
path String: path
file_type String: file extension, Ex. (.json)
file_contents dict: data to be exported
file_name String: optional file name
"""
# Create .json file
if file_type == ".json":
FileHandler.create_json_file(path, file_name, file_contents)
# Create .csv file
if file_type == ".csv":
FileHandler.create_csv_file(path, file_name, file_contents)
# Create .xml file
if file_type == ".xml":
FileHandler.create_xml_file(path, file_name, file_contents)
@staticmethod
def create_dir(dir_name, path):
"""
Provide simple API for creating a directory.
Parameters:
dir_name str: Name of the directory
path str: Path of the directory
"""
path = path + "/" + dir_name
print("Current Path: "+path)
os.mkdir(path)
return path
@staticmethod
def create_json_file(path, file_name, py_dict):
with FileHandler.file_opener(path, file_name, ".json") as json_file:
json_object = json.dumps(py_dict, indent=2)
json_file.write(json_object)
json_file.close()
@staticmethod
def create_csv_file(path, file_name, py_dict):
with FileHandler.file_opener(path, file_name, ".csv") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=FileHandler.create_field_names(py_dict))
writer.writeheader()
writer.writerow(py_dict)
@staticmethod
def create_xml_file(path, file_name, py_dict, root_name="Project_Configuration"):
root = ET.Element(root_name)
for key in list(py_dict.keys()):
e = ET.SubElement(root, key)
for key_n in list(py_dict[key].keys()):
ET.SubElement(e, key_n).text = py_dict[key][key_n]
tree = ET.ElementTree(root)
tree.write(path+"/"+file_name+".xml")
@staticmethod
def prompt_file_open():
app = QApplication(sys.argv)
path = QFileDialog.getOpenFileName()[0]
return FileHandler.parse_file_info(path)
@staticmethod
def prompt_file_save():
app = QApplication(sys.argv)
path = QFileDialog.getSaveFileName(filter="CSV files (*.csv);; XML files (*.xml)")
if path[1] == 'XML files (*.xml)':
new_path = path[0]+".xml"
elif path[1] == 'CSV files (*.csv)':
new_path = path[0]+".csv"
return FileHandler.parse_file_info(new_path)
@staticmethod
def prompt_dir():
app = QApplication(sys.argv)
return QFileDialog.getExistingDirectory()
@staticmethod
def file_opener(path, file_name, file_type, flag="w"):
return open(path + "/" + file_name + file_type, flag)
@staticmethod
def parse_file_info(path):
if not path:
return []
file_name_split = FileHandler.get_path_last(path, "/").split(".")
path = FileHandler.remove_path_last(path, 1)
file_name = file_name_split[0]
file_type = "." + file_name_split[1]
return [path, file_name, file_type]
@staticmethod
def get_path_last(path, delimiter="/"):
return path.split(delimiter)[-1]
@staticmethod
def remove_path_last(path, remove_count):
return "/".join(path.split("/")[:-remove_count])
@staticmethod
def create_field_names(py_dict):
key_list = []
for key in py_dict:
key_list.append(key)
return key_list