データベースを作成する必要があり、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 ファイルも必要です。