在Python中附加列表

时间:2014-07-01 16:17:05

标签: python list save

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

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',....] 

1 个答案:

答案 0 :(得分:1)

只需更改

emptyList = [] # create empty list

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

如果您的列表已经存在,那么您将加载它...虽然它不再是“emptyList”