How to write a dictionary into an existing file?

后端 未结 4 729
-上瘾入骨i
-上瘾入骨i 2020-12-10 03:36

Let\'s say I have a dictionary and I want to write it into an existing file. How can I do so without losing anything that could potentially already exist in the file? What I

4条回答
  •  心在旅途
    2020-12-10 04:02

    pickle may be another choice:

    import pickle
    
    output = open('output.txt', 'ab+')
    data = {'a': [1, 2, 3],}
    
    pickle.dump(data, output)
    output.close()
    
    # read data
    output = open('output.txt', 'rb')
    obj_dict = pickle.load(output)    # 'obj_dict' is a dict object
    

    But only the data that has been serialized by pickle could be read using pickle.load. So if you want to read all data from the file, you should pickle.dump all the data into the file.

提交回复
热议问题