This sample, demonstrates how to write and read a python dict data as a json object to a file
{
"a": "1",
"b": "2"
}
#!/usr/bin/python3
import os
from JsonHelper import JsonHelper
# init dirs
dir_path = os.path.dirname(os.path.realpath(__file__))
# You can give an extension to the file like Local State.json
file_path = dir_path + "/Local State"
# init jsonHelper
jsonHelper = JsonHelper()
# our data to write as json.
myDict = {"a":"1", "b":"2"}
# write task
jsonHelper.writeData(file_path, myDict)
# read task
data = jsonHelper.readData(file_path)
# Print for debug.
# You can also check
# the Local State file in working directory.
print(data)
#!/usr/bin/python3
import json
import os.path
from Log import Log
from Error import Error
class JsonHelper():
def __init__(self):
self.TAG = "JsonHelper"
self.log = Log("my-python3-json-write-read-sample")
def readData(self, filePath):
if os.path.exists(filePath):
try:
with open(filePath) as json_file:
data = json.load(json_file)
return data
except Exception as e:
self.log.e(self.TAG, Error.ERROR_1010, e)
def writeData(self, filePath, data):
try:
with open(filePath, 'w+') as outfile:
json.dump(data, outfile, indent=4)
except Exception as e:
self.log.e(self.TAG, Error.ERROR_1011, e)
#!/usr/bin/python3
import os
import errno
import datetime
class Log():
def __init__(self, appConfigFolderName):
self.TAG = "FileLog"
self.logErrorOn = True
self.logDebugOn = True
self.logInfoOn = True
self.ERROR_TAG = "Log e"
self.DEBUG_TAG = "Log d"
self.INFO_TAG = "Log i"
dirPath = os.path.expanduser("~") + "/.cache/" + appConfigFolderName
self.makeDirIfNotExist(dirPath)
self.filePath = dirPath + "/log"
# gets datatime
def getDateTime(self):
return datetime.datetime.now()
#makes dir
def makeDirIfNotExist(self, path):
if (path is not ""):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
########################
# Error log
########################
def e(self, TAG, msg, e):
if (self.logErrorOn):
eArgsText = ""
for arg in e.args:
eArgsText = eArgsText + arg + " "
logText = "\n[%s %s in %s] :\n%s\n%s\n%s\n" % (self.getDateTime(), self.ERROR_TAG, TAG, str(msg), type(e).__name__, eArgsText)
with open(self.filePath, "a+") as file:
file.write(logText)
########################
# Debug log
########################
def d(self, TAG, msg):
if (self.logDebugOn):
logText = "\n[%s %s in %s] :\n%s\n" % (self.getDateTime(), self.DEBUG_TAG, TAG, str(msg))
with open(self.filePath, "a+") as file:
file.write(logText)
########################
# İnfo log
########################
def i(self, TAG, msg):
if (self.logInfoOn):
logText = "\n[%s %s in %s] :\n%s\n" % (self.getDateTime(), self.INFO_TAG, TAG, str(msg))
with open(self.filePath, "a+") as file:
file.write(logText)
#!/usr/bin/python3
class Error():
ERROR_1010 = "Error:1010"
ERROR_1011 = "Error:1011"
srdr@aspr:~/Desktop/my-python3-json-write-read-sample$ python3 app.py
{
"a": "1",
"b": "2"
}