SourD SourD - 1 year ago 70
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 Source

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:


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":

At the end, close the file again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download