Search code examples
pythonfileinput

How to delete a specific line in a text file using Python?


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


Solution

  • 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.