我是一名大学生,必须准备一堂Python课程,以便为9年级的课程做准备。我创建了一个地址簿程序,允许他们创建地址簿并添加条目并查看书籍。
我无法弄清楚的一个部分是如何编辑条目。您基本上必须能够从多行中选择一行,然后键入将保存在原始行上的新数据。
最初添加条目时,我会在单独的变量中输入名称,年龄,地址和城市,然后将它们写入文本文件,并在它们之间使用逗号。
由于我通常不使用Stack Overflow,因此我不确定要提供哪些信息,所以如果您需要更多信息或代码,请告诉我们!
谢谢! 大卫
编辑我已添加以下所有代码。它打印到文本文件并用逗号分隔。
def createAddBook():
f = open("address_book.txt", "w")
def viewAddBook():
f = open("address_book.txt", "r")
contacts = f.read()
print(contacts)
print()
f.close
def addEntry():
addList = []
Name = input("What is the name?" + "\n")
Age = input("What is the age?" + "\n")
Address = input("What is the address?" + "\n")
City = input("What is the city?" + "\n")
addList.append(Name + ", ")
addList.append(Age + ", ")
addList.append(Address + ", ")
addList.append(City + "\n")
f = open("address_book.txt", "a")
for entry in addList:
f.write(entry)
f.close()
inuse = True
while inuse == True:
choice = input("Do you have an address book? (yes/no)" + "\n")
if choice == "yes":
choice = input("Would you like to view, add or edit your address book? (view/add/edit)" + "\n")
if choice == "view":
viewAddBook()
elif choice == "edit":
editEntry()
elif choice == "add":
addEntry()
elif choice == "no":
createAddBook()
print("Address book has been created!")
choice = input("Would you like to add an entry to the address book? (yes/no)" + "\n")
if choice == "yes":
addEntry()
elif choice == "no":
inuse = False
elif choice == "close":
break
答案 0 :(得分:0)
我了解您要将地址簿创建为CSV文件(每行存储一个条目,并使用逗号分隔给定条目的字段)。那是你的目标吗?要管理这样的文件,最简单的解决方案是使用标准Python库中的csv
模块。以下是文档页面的链接: