How to delete specific line in text file?

Question:

I’m making a joke program that has a text file storing jokes. On program load, it grabs all the lines from the file and assigns them to a jokes list Everything but the remove joke function is working. Whenever you call remove joke, it ends up re-writing every line in the text file to an empty string instead of the selected line

When running this function, it does remove the joke from the jokes list properly

def remove_joke():
    for i in range(len(jokes)):
        print(f"{i}t{jokes[i]}")
    
    remove_index = int(input("Enter the number of the joke you want to remove:t"))

    with open("jokes.txt", "r") as f:
        lines = f.readlines()
    with open("jokes.txt", "w") as f:
        for line in lines:
            print(line)
            if line == jokes[remove_index]:
                f.write("")
    jokes.remove(jokes[remove_index])
Asked By: Zach Reese

||

Answers:

Instead of

            if line == jokes[remove_index]:
                f.write("")

you want:

            if line != jokes[remove_index]:
                f.write(line+'n')

Or even:

            if line != jokes[remove_index]:
                print(line, file=f)
Answered By: Tim Roberts
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.