0
    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.

almond6
  • 19
  • 4
  • You are actually comparing each line with the input that you gave and write it only if this input matches the line. In your example, you probably had a line that matched the input and then only this was written to the file. – elyptikus Oct 17 '22 at 11:11

1 Answers1

0

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.

easyliving
  • 1
  • 1
  • 2