我是Python(以及一般编程)的新手,正在为一个典型的类制作一个数据库/寄存器。我希望用户能够在数据库中添加和删除学生,我主要使用列表来实现此目的,但遇到了困难。
每当我重新启动程序时,用户修改的列表都会返回到我在代码中指定的默认列表。我浏览了互联网并尝试将列表保存到单独的 txt 文件中。然而,每次我重新启动程序时,txt 文件也会恢复为默认值。我希望您能给我一种方法来保存对列表所做的更改并保持这种状态。这是代码(不是很好):
def menu():
print "*****************CLASS REGISTER*****************"
print "Press 1 See The List Of Pupils"
print "Press 2 To Add New Pupils"
print "Press 3 To Remove Pupils"
print "Press 0 To Quit \n"
filename = open('pupil.txt','r')
pupil = ["James Steele", "Blain Krontick", "Leeroy Jenkins", "Tanvir Choudrey"]
def see_list(x):
print x
def add_pupil(x):
print "You have chosen to add a new pupil.\n"
option = raw_input("Please type the childs name.")
x.append(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been added to the system."
return x
def delete_pupil(x):
print "You have chosen to remove a pupil.\n"
option = raw_input("Please type the childs name.")
if option in x:
x.remove(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been removed from the system."
else:
print "That person is not in the system."
return x
one = 1
while one != 0:
menu()
option = input()
if option == 1:
see_list(pupil)
elif option == 2:
add_pupil(pupil)
elif option == 3:
delete_pupil(pupil)
elif option == 0:
break
else:
print "That is not a valible choice."
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
if option == 0:
quit
最佳答案
好吧,您只需打开 pupil.txt
文件,但从未读回其内容。你需要这样的东西:
filename = open('pupil.txt', 'r')
contents = filename.read()
filename.close()
pupil = [name for name in contents.split('\n') if name]
此外,您还需要处理 pupil.txt
文件不存在的情况;这可以通过 IO 调用周围的 try.. except
block 来完成。
最后,正如上面的评论之一所提到的,看一下 pickle
模块,它允许您将 Python 对象存储在 Python 内部格式的文件中(实际上不可读,但可以为您省去很多麻烦)。
关于python - 在 Python 中保存/加载列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10658818/