0

I have a function that I want to use to delete a set of lines in a file called Schedule.txt. I want it to delete 6 lines in total, with an input at the beginning, asking the user which time to delete, which is the first out of six lines. This is as far as I've got. If anyone can help me to delete the 6 lines, please answer!

def delete ():
    train = int(input("Enter the train time that you want to remove: "))
    file = open("Schedule.txt", "r")
    file.read("|  Train: "+train)
Robski
  • 19
  • 1
  • 4

1 Answers1

0

How about this?

import fileinput
import sys

def delete ():

    train = input("Enter the train time that you want to remove: ")
    train = train.strip()

    # REMEMBER WHICH LINE THE TRAIN WAS FOUND ON
    train_found_on = None

    # OPEN THE FILE FOR IN-PLACE WRITING
    for i, line in enumerate(fileinput.input('schedule.txt', inplace=1)):

        # NEVER WRITE OUT THE LINE WHERE THE TRAIN WAS MATCHED
        if 'Time:' in line and train in line:
            train_found_on = i
            continue

        # NOR THE LINES AFTER IN THAT BLOCK
        if train_found_on and i < (train_found_on + 7):
            continue

        # BUT WRITE OUT THE OTHERS
        sys.stdout.write(line)

See also this post: How do I modify a text file in Python?

Community
  • 1
  • 1
Harry
  • 3,312
  • 4
  • 34
  • 39