需要创建数据库,我正在努力从 txt 文件中删除。
我不知道如何让它从读取变量中删除 nameToFind。有人建议我使用字典?这是我到目前为止所拥有的:
def displayMenu():
print ("1 - Add item")
print ("2 - Delete item")
print ("3 - Find item using name")
print ("4 - Find item using score")
print ("5 - Update score")
print ("9 - Quit")
def getMenuChoice():
try:
choice = int(input("Please enter your choice:"))
except Exception:
return 0
else:
return choice
def addItem(newName, newScore, datafile):
myFile = open(datafile, "a")
myFile.write(newName + ":" + newScore + "\n")
myFile.close()
def deleteItem(nameToFind, datafile):
deletedword = str(nameToFind)
myFile = open("datafile.txt", "r")
read = myFile.read()
for line in read:
lines = line.split(":")
#if lines == deletedword:
#deleted = read.remove(deletedword)
#print(deleted)
myFile.close()
deleted = read.remove[nameToFind]
print(deleted)
myFile1 = open("datafile.txt", 'w')
myFile1.write(deleted)
myFile1.close()
def findItemUsingName(nameToFind, datafile):
scores = {}
myFile = open("datafile.txt", 'r')
for line in myFile:
lineValues = line.split(":")
scores[lineValues[0]] = lineValues[1]
myFile.close()
highestScores = {}
choice = 0
while choice in [1, 2, 3, 4, 5, 0]:
displayMenu()
choice = getMenuChoice()
if choice == 0:
print ("Please enter 1, 2, 3, 4, 5 or 9")
elif choice == 1:
newName = input("Please enter the new name:")
try:
newScore = int(input("Please enter score for " + newName + ":"))
except Exception:
print("You must enter an integer for score")
else:
addItem(newName, str(newScore), "datafile.txt")
elif choice == 2:
print("Delete item")
nameToFind = input("What is the name to delete? ")
deleteItem(nameToFind, "datafile.txt")
elif choice == 3:
print("Find item using name")
nameToFind = input("What is the name to find? ")
findItemUsingName(nameToFind, "datafile.txt")
elif choice == 4:
print("Find item using score")
elif choice == 5:
print("Update score")
您还需要一个名为“datafile”的 .txt 文件。