如何在python中删除一行文本(最小可复制示例)



我用来从文件中删除一行的代码是删除文本文件中的所有内容,而不是包括我输入的名称的行。有解决办法吗?如果有,请演示一下?

def playerMenu():
runningplayer = True
while runningplayer == True:
time.sleep(0.3)
print("n====================================================")
print("************Welcome to The Player Menu**************")
print("====================================================")
time.sleep(0.2)
choice = input('''
========================================================
A: Add Player & Score
B: Delete Player
C: View Scores
D: Back To Main Menu
E: Exit Menu
========================================================
nPlease select what you wish to do: ''')
#This ELIF statement will allow the user to write the name and score of the player.
if choice == "A" or choice == "a":
save_name = input('Enter your name. ').title()
save_score = input('Enter your score. ')
text_file = open("highscores.txt", "a")
text_file.write("n" + save_name + ' | ' + save_score + "n")
text_file.close()
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()

#This ELIF statement will allow the user to delete a player from the text file.
elif choice == "B" or choice == "b":
print("These are the current players and their score")
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()
time.sleep(0.3)
save_delete = input("Please enter the name of the player you wish to delete: ")
with open("highscores.txt", "r") as f:
lines = f.readlines()
with open("highscores.txt", "w") as f:
for line in lines:
if line.strip("n") != save_delete:
f.write(lines)
print(lines)

我为您带来了选项B部分代码,并对其进行了一些修改。然后,我在需要删除的行的名称中包含了分隔字符(以确保考虑到整个名称(。

我的测试文本文件的内容如下所示:bert|10\nbertha|9\nsam|8\nben|8\nhailey|6

我的测试代码如下:

import time
print("These are the current players and their score")
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print(whole_thing)
text_file.close()
time.sleep(0.3)
save_delete = input("Please enter the name of the player you wish to delete: ") + "|"
print(f"save_delete = {save_delete}")
with open("highscores.txt", "r") as f:
lines = f.readlines()
print(lines)
with open("highscores.txt", "w") as f:
for line in lines:
if not(line.startswith(save_delete)):
f.write(line)

如果我运行这个,并选择te delete"bert";,它只删除了bert(而不是bertha(。我的文本文件的内容导致:bertha|9\nsam|8\nben|8\nhailey|6

最新更新