simple helper to load (json) files into dicts
This commit is contained in:
parent
cce6e058c2
commit
adff0f724f
38
datafiles.py
Normal file
38
datafiles.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
class DataFile(dict):
|
||||||
|
def __init__(self, filename: str, create: bool):
|
||||||
|
super().__init__()
|
||||||
|
self.__filename = filename
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.stat(self.__filename)
|
||||||
|
except OSError as e:
|
||||||
|
if not create:
|
||||||
|
raise e
|
||||||
|
|
||||||
|
self.load()
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class JSONFile(DataFile):
|
||||||
|
def __init__(self, filename: str, create: bool):
|
||||||
|
super().__init__(filename, create)
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
with open(self.__filename, "U") as f:
|
||||||
|
json_dict = json.loads(f.read())
|
||||||
|
|
||||||
|
for k in json_dict:
|
||||||
|
self[k] = json_dict[k]
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
with open(self.__filename, "w") as f:
|
||||||
|
f.write(json.dumps(self.copy()))
|
||||||
Loading…
Reference in New Issue
Block a user