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

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:

You need to strip(n) the newline character in the comparison because if your file doesnt end with a newline character the very last line wont either.

Solution to this problem with only a single open:

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

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.

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

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:

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

Leave a Reply

Your email address will not be published. Required fields are marked *