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

如何使用Pickle在python的另一个文件中添加到列表中?,python,list,append,pickle,Python,List,Append,Pickle,我一直在尝试附加到另一个文件中的列表,我也在尝试这样做,如果其中包含3个以上的变量,它会删除最早添加的变量并添加新数据,这让我非常困惑,这是我迄今为止的代码: with open ("TestScores_Class1.txt","ab") as a: Class1Score = [name, points] Class1Scorelen = (Class1Score,a) if len(Class1Scorelen) > 3: del (Class

我一直在尝试附加到另一个文件中的列表,我也在尝试这样做,如果其中包含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()

试着把你的程序分成几个小的逻辑段。您正在尝试做三件事:

  • 从文件加载列表
  • 修改列表
  • 将列表保存到文件
清楚地将每个动作分开应该可以简化事情

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)

当您将
一起使用时,不需要
a.close()
,它会被明确地删除。您可能应该在某个时候使用
pickle.load
pickle.load
。如果len(data)>3:检查,则不需要使用
if-len(data)>3:
检查。