How to delete a specific line in a file? How to delete a specific line in a file? python python

How to delete a specific line in a file?


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.


Solution to this problem with only a single open:

with open("target.txt", "r+") as f:    d = f.readlines()    f.seek(0)    for i in d:        if i != "line you want to remove...":            f.write(i)    f.truncate()

This solution opens the file in r/w mode ("r+") and makes use of seek to reset the f-pointer then truncate to remove everything after the last write.


The best and fastest option, rather than storing everything in a list and re-opening the file to write it, is in my opinion to re-write the file elsewhere.

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

That's it! In one loop and one only you can do the same thing. It will be much faster.