Csarg
Csarg

Reputation: 363

Python: Checking for JSON files and creating one if needed

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")

Upvotes: 8

Views: 31620

Answers (4)

Noam Chonky
Noam Chonky

Reputation: 51

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)

Upvotes: 5

Ryan
Ryan

Reputation: 9

w+ opens with write permissions.
The + creates a new file if one is not found.

filename = 'jsonDB.json'

def openFile():
    with open(filename, 'w+') as f:
    f.write('{}')            
    f.close

openFile()

Upvotes: -3

Misa
Misa

Reputation: 61

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)

Upvotes: 6

Lucas Infante
Lucas Infante

Reputation: 808

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({}))

Upvotes: 10

Related Questions