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({}))
Answer from Lucas Infante on Stack OverflowI 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)
Videos
I don't think you can append using json.dump, you'll have to handle it with something like this.
import os
import json
import time
fname = "test.json"
data = {'key1': 1, 'key2': {'k2a': 2.1, 'k2b': 2.2}}
if os.path.exists(fname):
#read existing file and append new data
with open(fname,"r") as f:
loaded = json.load(f)
loaded.append({'appended': time.time()})
else:
#create new json
loaded = [data]
#overwrite/create file
with open(fname,"w") as f:
json.dump(loaded,f)
You cannot append to a json-file as such. See the json file as one (serialized) python object, in your case a dictionary.
You could load the json file (if it's there), and if not initialise it as en empty dict.
Then add the data that you wish and save it again (in one piece).
import json
import time
fname = 'test.json'
loaded = {}
try:
with open(fname, "r") as f:
loaded = json.load(f)
except IOError:
# may complain to user as well
pass
loaded['appended'] = time.time()
with open(fname, "w") as f:
json.dump(loaded, f)
try this
import simplejson as json
import os
if os.path.isfile("./ages.json") and os.stat("./ages.json").st_size !=0:
old_file = open("./ages.json", "r+")
data = json.loads(old_file.read())
print("current age is", data["age"], "Adding User" )
data["age"] = data["age"] + 1
print("New Age is ", data["age"])
else:
old_file = open("./ages.json", "w+")
data = {"name": "Nick", "age": 26}
print("No default file Found Setting default age to ", data["age"])
old_file.seek(0)
old_file.write(json.dumps(data))
Your logic isn't quite correct.
I'd suggest handling the non existence first, then load the file regardless (because it must exist then)
import simplejson as json
import os
filename = 'ages.json'
f = None
# checks if the file doesn't exists or if the file is empty
if not os.path.isfile(filename) or os.stat(filename).st_size == 0:
f = open(filename, "w")
data = {"name": "Helio", "age": 88}
print("No file Found, setting default age to", data["age"])
json.dump(data, f)
if not f: # open the file that exists now
f = open(filename)
data = json.load(f)
f.close() # close the file that was opened in either case
# Print the data from the file
print("Current age is", data["age"], "-- adding a year.")
data["age"] = data["age"] + 1
print("New age is", data["age"])
data is a Python dictionary. It needs to be encoded as JSON before writing.
Use this for maximum compatibility (Python 2 and 3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
See json documentation.
To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
The code is simpler in Python 3:
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
On Windows, the encoding='utf-8' argument to open is still necessary.
To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
The codecs.getwriter call is redundant in Python 3 but required for Python 2
Readability and size:
The use of ensure_ascii=False gives better readability and smaller size:
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.
Python's pathlib is quite convenient to use for this task:
import json
from pathlib import Path
data = ['steve','martin']
season = '2019-2020'
Paths of the new directory and json file:
base = Path('Best')
jsonpath = base / (season + ".json")
Create the directory if it does not exist and write json file:
base.mkdir(exist_ok=True)
jsonpath.write_text(json.dumps(data))
This will create the directory relative to the directory you started the script in. If you wanted a absolute path, you could use Path('/somewhere/Best').
If you wanted to start the script while beeing in some other directory and still create the new directory into the script's directory, use: Path(__file__).resolve().parent / 'Best'.
First of all, instead of doing everything in same place have a separate function to create folder (if already not present) and dump json data as below:
def write_json(target_path, target_file, data):
if not os.path.exists(target_path):
try:
os.makedirs(target_path)
except Exception as e:
print(e)
raise
with open(os.path.join(target_path, target_file), 'w') as f:
json.dump(data, f)
Then call your function like :
write_json('/usr/home/target', 'my_json.json', my_json_data)
So I have a simple program to write something to a json file but it doesn't write anything to it after I open the file. the file is in the same directory but nothing happens, what am I doing wrong?
import json
dic = {}
for i in range(10):
dic[i] = i
print(dic)
with open("dict.json", "w") as outfile:
json.dump(dic, outfile)