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")
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({}))
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With