Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Checking for JSON files and creating one if needed

Tags:

python

I'm currently making a program that requires a JSON database file. I want the program to check for the file, if it's there then it's perfect, run the rest of the program, but if it doesn't exist create 'Accounts.json' with {} inside the file, instead then run the program.

How would I do this? Whats the most efficient way.

Note: I use this for checking, but how would I create the file:

def startupCheck():
    if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
        # checks if file exists
        print ("File exists and is readable")
    else:
        print ("Either file is missing or is not readable")
like image 959
Csarg Avatar asked Oct 07 '15 11:10

Csarg


3 Answers

I believe you could simply do:

import io
import json
import os

def startupCheck():
    if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
        # checks if file exists
        print ("File exists and is readable")
    else:
        print ("Either file is missing or is not readable, creating file...")
        with io.open(os.path.join(PATH, 'Accounts.json'), 'w') as db_file:
            db_file.write(json.dumps({}))
like image 81
Lucas Infante Avatar answered Nov 14 '22 22:11

Lucas Infante


This is how i did it. I hope it helps. edit, yeey it looks like a code now :D

import json
import os

def where_json(file_name):
    return os.path.exists(file_name)


if where_json('data.json'):
    pass

else:

    data = {  
        'user': input('User input: '),
        'pass': input('Pass input: ')
    }


    with open('data.json', 'w') as outfile:  
        json.dump(data, outfile)
like image 43
Misa Avatar answered Nov 14 '22 23:11

Misa


How about wrapping the open file in a try/except? I'm not a professional Python coder, so feel free to weigh in if this is not a kosher approach.

try:
    with open('Accounts.json', 'r') as fp:
        accounts = json.load(fp)

except IOError:
    print('File not found, will create a new one.')
    accounts = {}

# do stuff with your data...
with open('Accounts.json', 'w') as fp:
    json.dump(accounts, fp, indent=4)
like image 20
Noam Chonky Avatar answered Nov 14 '22 22:11

Noam Chonky