JuhiSi
JuhiSi

Reputation: 9

How to remove a specific line in a text file without leaving a blank line behind?

My code:

with open("file_name.txt", "r") as f:
    lines = f.readlines()

with open("file_name.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != thing_to_be_deleted:
            f.write(line)

The problem is that this leaves a blank line behind in the file.

Upvotes: 0

Views: 60

Answers (2)

Santi Rodriguez
Santi Rodriguez

Reputation: 304

When you use the readlines() method, you are transforming your file into a list, where each line of your file is a value in the list. So you can use list methods in order to manage that file content. Specifically the remove() method whill help you. Example:

with open("file_name.txt", "r") as f:
    lines = f.readlines()
    line_to_delete = f'{thing_to_be_deleted}\n'
    while line_to_delete in lines:
        lines.remove(line_to_delete)

with open("file_name.txt", "w") as f:
    for line in lines:
        f.write(line)

Upvotes: 1

Jan
Jan

Reputation: 43179

You could use a regular expression:

import re

needle = "^" + thing_to_be_deleted + r"\n?"
text = re.sub(needle, "", text, re.M)

See a demo on regex101.com.

Upvotes: 0

Related Questions