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

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

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.

Leave a Comment