Last active
October 22, 2021 19:49
-
-
Save entirelymagic/d3b45d07eaa0a9a745484c76ef401720 to your computer and use it in GitHub Desktop.
JsonFileHandler/Serializer/Deserializer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
class JsonFileHandler: | |
"""Given the name of the json file location, data can be extracted or added. | |
If the location does not exists it will be created. | |
""" | |
def __init__(self, file_name: str) -> None: | |
self.file = file_name | |
def check_if_folder_or_file_exists(self) -> None: | |
if not os.path.isfile(self.file): | |
with open(self.file, 'w') as f: | |
json.dump({}, f) | |
# if a folder from the file name does not exist, create it | |
def create_folder_and_file(self) -> None: | |
if not os.path.exists(os.path.dirname(self.file)): | |
os.makedirs(os.path.dirname(self.file)) | |
with open(self.file, "w") as f: | |
json.dump({}, f) | |
def deserialize(self) -> dict: | |
self.check_if_folder_or_file_exists() | |
with open(self.file) as f: | |
content = json.load(f) | |
return content | |
def serialize(self, data:any) -> None: | |
with open(self.file, "w") as f: | |
json.dump(data, f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment