WhatsThePoint WhatsThePoint - 4 days ago 6
Python Question

Removing names from a text file

another issue I have encountered, I have this code to remove a name from a text file. I am not exactly sure why but sometimes it works fine and does remove the name, but quite often it doesn't, is there a better way of doing this that works 100% of the time? I have changed my filepath and filename as you guys don't need it.

with open(r"MyFilePath\MyFile.txt","r") as file:
participants=[]
for line in file:
participants.append(line)
file.close()
leavingParticipant=input("Enter leaving participant: ")
file=open(r"MyFilePath\MyFile.txt","w")
for participant in participants:
if participant!=leavingParticipant+"\n":
file.write(participant)
file.close()

Answer
with open(r"MyFilePath\MyFile.txt","r") as file:
    participants=[]
    for line in file:
        participants.append(line)

leavingParticipant=input("Enter leaving participant: ")

with open(r"MyFilePath\MyFile.txt","w") as file:
    for participant in participants:
        if leavingParticipant != participant.strip():
            file.write(participant)

You don't need to manually close files in context managers (The with..as statements). Instead of trying to play with the whitespace around the information we need, let's just remove it for our comparison.

Comments