3.09.2017 г.

Python use picke to write json to faile and read back to dictionary

#import module
from pprint import pprint  # pretiprint
import json
import os
import pickle
# hard code param
test_file = 'test_file.json'
db = {}
dl = {}

def check_file_exists(filename):
    ''' Check file exists or not '''
    if not os.path.exists(filename):
        open(filename, 'w').close()

def write_in_json(filename, db):
    ''' Write dictionary to file with ekstension json'''
    db = json.dumps(db)
    with open(filename, 'wb') as f:
        pickle.dump(db, f)

def load_from_json_file(filename, dl):
    ''' Load serial object into file to dictionary '''
    json_file = open(filename, 'rb')
    dl = pickle.load(json_file)
    dlj = json.loads(dl)
    return dlj

# Get from enywere for test
borko = {'name': 'Borko', 'ip': '192.168.168.1', 'df': 30000, 'free': 'dev'}
sue = {'name': 'Sue Somebody', 'ip': '192.168.168.2', 'df': 40000, 'free': 'hdw'}
tom = {'name': 'Tom Aks', 'ip': '192.168.168.3', 'df': 0, 'free': None}

db['bob'] = borko
db['sue'] = sue
db['tom'] = tom
if __name__ == '__main__':
    # Create file if not exists uncoment to begin
    # check_file_exists(test_file)
    # function write json to file uncoment to begin
    #write_in_json(test_file, db)
    # fuction load picke file to json object return to dictionary
    #print(load_from_json_file(test_file, dl))

1 коментар :