我一直试图将其附加到另一个文件内的列表中,我也试图这样做,以便如果其中有超过 3 个变量,它会删除最旧添加的变量并添加新的数据......
我一直试图将其附加到另一个文件内的列表中,我也试图这样做,如果其中有超过 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)