我需要先创建一个空列表,然后插入一个元素并将其保存到磁盘。然后再次从磁盘读取列表,并将另一个元素添加到列表,然后再次将列表保存到磁盘,然后再次读取列表,并保存另一个元素以进行进一步的操作,依此类推。我当前的代码:

import pickle
emptyList = [] # create empty list
x = 'john' #this data is coming from client, so will change on each server call
emptyList.append(x) # append element
with open('createList.txt', 'wb') as f: # write to file
      pickle.dump(emptyList, f)
with open('createList.txt', 'rb') as f: # read from file
      my_list = pickle.load(f)
print my_list # print updated list


现在,我得到的是这样的更新列表:

#if x = 'john' then I get
['john']
#if x = 'george' then I get
['george']
#if x = 'mary' then I get
['mary']
# ..... and so on


我要添加的元素是这样的:

['john','george','mary',....]

最佳答案

只是改变

emptyList = [] # create empty list




emptyList = [] if not os.path.exists("createList.txt") else pickle.load(open("createList.txt"))


这样,如果您的列表已经存在,则将其加载...尽管它不再是“ emptyList”

10-06 05:52