Append list of Python dictionaries to a file without loading it

前端 未结 4 1006
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 11:45

Suppose I need to have a database file consisting of a list of dictionaries:

file:

[
  {\"name\":\"Joe\",\"data\":[1,2,3,4,5]},
  {   ...                         


        
4条回答
  •  没有蜡笔的小新
    2021-02-03 12:20

    Using the same approach as user3500511...

    Suppose we have two lists of dictionaries (dicts, dicts2). The dicts are converted to json formatted strings. Dicts is saved to a new file - test.json. Test.json is reopened and the string objects are formatted with the proper delimiters. With the reformatted objects, dict2 can be appended and the file still maintains the proper structure for a JSON object.

    import json
    
    dicts = [{ "name": "Stephen", "Number": 1 }
             ,{ "name": "Glinda", "Number": 2 }
             ,{ "name": "Elphaba", "Number": 3 }
             ,{ "name": "Nessa", "Number": 4 }]
    
    dicts2= [{ "name": "Dorothy", "Number": 5 }
             ,{ "name": "Fiyero", "Number": 6 }]
    
    
    f = open("test.json","w")
    f.write(json.dumps(dicts))
    f.close()
    
    f2 = open("test.json","r+")
    f2.seek(-1,2)
    f2.write(json.dumps(dicts2).replace('[',',',1))
    f2.close()
    
    f3 = open('test.json','r')
    f3.read()
    

提交回复
热议问题