Skip to content

Instantly share code, notes, and snippets.

@serdarsen
Last active June 23, 2018 18:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serdarsen/c6b65f611d55d219f9b58cb8afd503e3 to your computer and use it in GitHub Desktop.
Save serdarsen/c6b65f611d55d219f9b58cb8afd503e3 to your computer and use it in GitHub Desktop.
This sample, demonstrates how to write and read a python dict data as a json object to a file

My Python3 Json Write Read Sample

This sample, demonstrates how to write and read a python dict data as a json object to a file


As a result Local State file

{
    "a": "1",
    "b": "2"
}

app.py

#!/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)

JsonHelper.py

#!/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)

Log.py

#!/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)

Error.py

#!/usr/bin/python3


class Error():

    ERROR_1010 = "Error:1010"
    ERROR_1011 = "Error:1011"

Usage

srdr@aspr:~/Desktop/my-python3-json-write-read-sample$ python3 app.py

As a result Local State file

{
    "a": "1",
    "b": "2"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment