SourD SourD - 7 months ago 7
Python Question

Deleting a specific line in a file (python)

Lets say I have a text file full of nicknames, how can I delete a specific nickname from that file?

Answer

Assuming your file is in the format of one nickname per line, use this.

First, open the file:

f = open("yourfile.txt","r")

Next, get all your lines from the file:

lines = f.readlines()

Now you can close the file:

f.close()

And reopen it in write mode:

f = open("yourfile.txt","w")

Then, write your lines back, except the line you want to delete. You might want to change the "\n" to whatever line ending your file uses.

for line in lines:
  if line!="nickname_to_delete"+"\n":
    f.write(line)

At the end, close the file again.

f.close()