How to delete a specific line in a file?

SourD picture SourD · Jan 17, 2011 · Viewed 428k times · Source

Let's say I have a text file full of nicknames. How can I delete a specific nickname from this file, using Python?

Answer

houbysoft picture houbysoft · Jan 17, 2011

First, open the file and get all your lines from the file. Then reopen the file in write mode and write your lines back, except for the line you want to delete:

with open("yourfile.txt", "r") as f:
    lines = f.readlines()
with open("yourfile.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != "nickname_to_delete":
            f.write(line)

You need to strip("\n") the newline character in the comparison because if your file doesn't end with a newline character the very last line won't either.