I am trying to append JSON objects to existing JSON object in text file. My first set of data look likes this.
data = [
{
"username": "Mike",
"code": "12345",
"city": "NYC"
}
]
Then I need to append another set of JSON objects to existing file to look like this:
data = [
{
"username": "Mike",
"code": "12345",
"city": "NYC"
},
{
"username": "Kelly",
"code": "56789",
"city": "NYC"
}
]
When I try to run:
with open('data2.txt', 'a') as outfile:
json.dump(data, outfile)
my data is not in correct JSON format. Can you please advise how to append to text file correctly?
解决方案
First read the data from the file.
with open('data2.txt') as data_file:
old_data = json.load(data_file)
Then append your data to the old data
data = old_data + data
Then rewrite the whole file.
with open('data2.txt', 'w') as outfile:
json.dump(data, outfile)