AfterHover
AfterHover

Reputation: 107

How to delete empty line from txt file after replacing it

Lets say I have a txt file that goes like this:

Line 1
Line 2
Line 3
a = input("text to delete from file: ")

with open('save.txt', 'r') as file:
    text = file.read()
with open('save.txt', 'w') as file:
    new_text = text.replace(a, '')
    file.write(new_text)

After the user has typed Line 2 as his input on the a variable, txt file goes like this:

Line 1
whitespace/empty line
Line 3

How can I delete the empty line?

Upvotes: 0

Views: 69

Answers (3)

Dini
Dini

Reputation: 149

This will save the text with no empy line to the variable final_text.

line_to_delete = "fifth line"

with open("data/test.txt") as file:
    text = file.read()
    print(text)
    text2 = text.replace(line_to_delete, "")

    text3 = [text for text in text2.splitlines() if text]
    final_text = " \n".join(text3) 
    print(final_text)

Upvotes: 0

Barmar
Barmar

Reputation: 781096

Split the input into a list of lines. Remove the lines that match the user's input, then join them back together.

a = input("text to delete from file: ")

with open('save.txt', 'r') as file:
    text = file.read().splitlines()
new_text = [line for line in text if line != a]

with open('save.txt', 'w') as file:
    file.write('\n'.join(new_text) + '\n')

Upvotes: 1

kindall
kindall

Reputation: 184211

Delete the newline as well as the user's text.

new_text = text.replace(a + '\n', '')

Upvotes: 1

Related Questions