我遇到python 3程序的问题。我正在尝试构建一个函数,使用用户输入删除文本文件中的特定行,但在我的生活中不能让它工作。由于我是初学者,我想知道是否有更多的人能帮助我建立这个功能。
Python 3代码:
def main():
players = load_results_from_file("user_res.txt")
while True:
show_menu()
user_choice = input("Välj alternativ: ")
print()
if user_choice == "1":
show_players(players)
elif user_choice == "2":
add_player(players)
elif user_choice == "3":
save_players(players, "user_res.txt")
elif user_choice == "4":
del_player(players)
elif user_choice == "5":
break
else:
print("Du angav ett felaktivt val, försök igen")
print("Ha en bra dag!")
def save_players(players, file_name):
my_file = open(file_name, "w")
for player in players:
my_file.write("{};{};{};{}\n".format(player["name"],
player["round_1"],
player["round_2"], player["round_3"]))
my_file.close()
print("Sparat!")
def add_player(players):
name = input("Ange namn: ")
round_1 = input("Ange varv 1: ")
round_2 = input("Ange varv 2: ")
round_3 = input("Ange varv 3: ")
players.append({
"name": name,
"round_1": round_1,
"round_2": round_2,
"round_3": round_3
})
def show_players(players):
print("*"*40)
print("Mini Golf")
print("*"*40)
for player in players:
print("{:15} {} {} {}".format(player["name"], player["round_1"],
player["round_2"], player["round_3"]))
print()
def show_menu():
print("Klubbmästerskap i minigolf")
print("*"*40)
print()
print("Meny")
print("*"*4)
print("1) Visa resultat")
print("2) Lägg till resultat")
print("3) Spara resultat")
print("4) Radera spelare")
print("5) Avsluta programmet")
def load_results_from_file(file_name):
players_list = []
try:
my_file = open(file_name, "r")
except:
my_file = open(file_name, "w").close()
print("INFO: Ingen fil hittades, så vi skapa den!")
return players_list
content = my_file.read()
for players in content.split("\n"):
try:
player = players.split(";")
players_list.append({
"name": player[0],
"round_1": player[1],
"round_2": player[1],
"round_3": player[1]
})
except:
pass
return players_list
def del_player(players):
delete_player = input("Ange spelaren du vill radera: ")
my_file = open("user_res.txt", "r")
lines = my_file.readlines()
my_file.close()
my_file = open("user_res.txt", "w")
for line in lines:
if delete_player not in lines:
my_file.write(line)
main()
部分文字是瑞典语,如果有必要,我会更改。但是我无法工作的功能是del_player。我希望用户使用delete_player输入他们想要删除的播放器,但到目前为止它不会从文本文件中删除任何内容。
答案 0 :(得分:1)
问题是肯定在源代码中标有一个小的TYPO'#(1)!!!':
def del_player(players):
delete_player = input("Ange spelaren du vill radera: ")
my_file = open("user_res.txt", "r")
lines = my_file.readlines()
my_file.close()
my_file = open("user_res.txt", "w")
for line in lines:
print(type(delete_player), delete_player, type(line), line) #(2) !!!
if delete_player not in line: #(1) !!!
my_file.write(line)
如果这没有解决问题,那么添加print()
(标记为#(2)!!!如上所述可以澄清delete_player
在line
中找不到的问题}。