How do I delete a specific line in a text file? (Python)

60 Views Asked by At
    print("These are the coffees and the quantities")
    print(f.read())
    time.sleep(1)
    text = input("What line number do you want to delete?")
    with open("coffee names.txt", "r+") as fp:
        lines = fp.readlines()

    with open("coffee names.txt", "w") as fp:
        for line in lines:
            if line.strip("\n") == text:
                fp.write(line)

I have tried this, but it does not seem to delete 1 line. It deletes the whole thing and puts what I have typed into the shell into the text file.

1

There are 1 best solutions below

2
easyliving On

If you are trying to delete a line by the line number, just use a counter to iterate over the lines list like this:

line_no = int(input("What line number do you want to delete?"))
with open("coffee names.txt", "w") as fp:
    for i in range(len(lines)):
        if i != line_no:
            fp.write(lines[i]) # Edit: fix 'fp.write(line)'

Note here line numbers start from 0, as in line number 0, line number 1, line number 2, etc.