我是python(和一般编程)的新手,我正在为一个典型的类创建一个数据库/寄存器。我希望用户能够在数据库中添加和删除学生,我主要使用列表但是已经遇到了问题。
每当我重新启动程序时,用户已修改的列表将返回到我在代码中指定的defualt列表。我环顾互联网并试图将列表保存到单独的txt文件中。但是,每次重新启动程序时,txt文件也会返回到defualt。我想请你给我一个方法来保存对列表所做的更改并保持这种方式。这是代码(它不是很好):
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
答案 0 :(得分:4)
好吧,您只需打开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
块来完成。
最后,正如上面提到的其中一条评论,请看一下pickle
模块,它允许您以Python的内部格式将Python对象存储在文件中(这不是真的可读,但可以节省你的时间)很多麻烦。
答案 1 :(得分:1)
直接与您的问题无关,但是:
one = 1
while one != 0:
...
很傻。您所需要的只是:
while True:
...
答案 2 :(得分:0)
这就是数据库的用途。使用sqlite
- 一个基于文件的简单数据库,其库来自bundled with python。