-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate.py
More file actions
119 lines (87 loc) · 3.87 KB
/
create.py
File metadata and controls
119 lines (87 loc) · 3.87 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
"""
This module contains function for inserting new instances of data in the
JSON file.
"""
import copy, json
# Function for sensible type conversion
def stringType(string: str):
try:
int(string)
return int
except ValueError:
try:
float(string)
return float
except ValueError:
return str
# Variable to indenting nesting
indent = 4
def populator(schema: dict, filePath: str):
"""
'create' function is for creating new instances of data. This is a recursive function
which recurses when the value of any key of the schema, that is a dictionary, is a
dictionary.
Proper indentation system has been implemented while countering nested dictionary for
a better UI and UX.
'stringType' function has been used for very sensitive case conversions.
"""
value = copy.deepcopy(schema)
global indent
arg = f'{" " * indent}'
for key in schema:
arg = f'{" " * indent}{key}: ' # Variable for variable indentation spaces for nested value taking
if type(schema[key]) == dict:
indent += 4
print(arg)
value[key] = populator(schema[key], filePath) # Recurse if the value of the key is a dictionary
indent -= 4
elif type(schema[key]) == list:
itemList = []
while True: # Looped input taking if the value of the key is list type
item = input(arg)
if item.lower() != "__end__":
if stringType(item.strip()) == int:
item = int(item)
elif stringType(item.strip()) == float:
item = float(item)
elif item.strip() == "":
item = None
else:
pass
itemList.append(item)
else:
break
value[key] = itemList
else: # Input taking for scalar value
item = input(arg)
if item.lower() != "end":
if stringType(item.strip()) == int:
item = int(item)
elif stringType(item.strip()) == float:
item = float(item)
elif item.strip() == "":
item = None
else:
pass
value[key] = item
return value
def create(schema: dict, filePath:str):
global indent
arg = f'{" " * indent}'
try:
with open(filePath, "r") as f:
data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
data = {}
while True:
entry_id = input(f"{arg}ID: ")
if entry_id in list(data.keys()):
print(f"Instance with ID {entry_id} already exists")
elif " " in entry_id:
print("ID can't have white spaces")
else:
break
new_record = populator(schema, filePath)
data[entry_id] = new_record
with open(filePath, "w") as f:
json.dump(data, f, indent=8)