Python - write/ADD a new record in file with Json format
-
26-10-2019 - |
Question
I want to add a new record at the end of my file Json, For now it contains
{
"1":
{
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
}
im reading this file like this :
try:
json_data=open ("/home/sage/content.txt")
data=json.load (json_data)
except IOError:
print "Can't open your file"
how to add a new record at the end of file.
Solution
After reading the data , you can't add to the file, you need to create a new file (with the same name if you want):
data['added_data'] = 'some data added'
write_file = open("/home/sage/content.txt", "w")
write_file.write(json.dumps(data))
OTHER TIPS
If you are using python 2.5 or newer you should use with
statement dealing with files:
import json
with open('content.txt', 'r') as f:
data = json.load(f)
data["2"] = {
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
with open('content.txt', 'w') as f:
json.dump(data, f)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow