Reputation: 35
my code works absolutely fine, the only issue I'm having is that after the text is deleted, there is a blank line where the text used to be. So when I view the text file, there is a massive empty gap between two players lines. An example of this would be:
John | 35
Thomas | 56
(Blank Line)
Timmy | 34
this is my code:
# 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 not(line.startswith(save_delete)):
f.write(line)
Upvotes: 1
Views: 93
Reputation: 463
I think you need to use "|" with space " |". Otherwise there won't be a catch in your data, see example as following:
save_delete = input("Please enter the name of the player you wish to delete: ") + "|"
if save_delete in "hello |":
print("Yes")
print(lines)
print(save_delete)
output:
Please enter the name of the player you wish to delete: hello ['hello |\n', 'world |\n', 'no to war |\n', 'peace at home |\n', 'peace in the world |'] hello| #<<<<<<<<<<<<<<<<<<<<<<<<<
when save_delete is changed as following
save_delete = input("Please enter the name of the player you wish to delete: ") + " |" # " |" has space.
we have a match, see following:
Please enter the name of the player you wish to delete: hello
Yes <<<<<<<<<<<<<<<<<<<<<<<<<<<<
['hello |\n', 'world |\n', 'no to war |\n', 'peace at home |\n', 'peace in the world |']
hello | <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Now, I am able to remove "Hello" from my text.
My text previously:
hello | world | no to war | peace at home | peace in the world |
My text after the program run:
world | no to war | peace at home | peace in the world |
see the code I used:
with open("text_text.txt", "w") as f:
for line in lines:
print(type(line))
print(line)
if save_delete not in line:
print("Yes")
f.write(line)
Last Edit:
Before it runs:
After it runs:
I have deleted the world and no empty line appeared.
Upvotes: 2