如何使用Pickle在python的另一个文件中添加列表?

时间:2015-02-04 12:58:23

标签: python list append pickle

我一直试图附加到另一个文件的列表中,我也试图这样做,如果它里面有超过3个变量,它会删除最新添加的变量并添加新数据,这会让人感到困惑我非常糟糕,这是我到目前为止的代码:

with open ("TestScores_Class1.txt","ab") as a:
    Class1Score = [name, points]
    Class1Scorelen = (Class1Score,a)
    if len(Class1Scorelen) > 3:
        del (Class1Score,a)[3]
    pickle.dump(Class1Score,a)
    a.close()

1 个答案:

答案 0 :(得分:1)

尝试将程序分解为小的逻辑段。你正试图做三件事:

  • 从文件
  • 加载列表
  • 修改列表
  • 将列表保存到文件

明确区分每个动作应该简化事情。

import pickle

to_add = ("Kevin", 42)

#Open the file and read its contents. 
#If the file is blank or doesn't exist, make an empty list.
try:
    with open("my_file.txt") as file:
        data = pickle.load(file)
except (EOFError, IOError):
    data = []

#add the item to the list. Shorten the list if it's too long.
data.append(to_add)
if len(data) > 3:
    data = data[-3:]

#Overwrite the file with the new data.
with open("my_file.txt", "w") as file:
    pickle.dump(data, file)