使用python在文件中选择一个后删除行

时间:2016-04-28 18:26:27

标签: python function file

我有一个函数,我想用它来删除名为Schedule.txt的文件中的一组行。我希望它总共删除6行,在开头输入,询问用户删除的时间,这是六行中的第一行。这就是我所拥有的。如果有人可以帮我删除6行,请回答!

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

1 个答案:

答案 0 :(得分:0)

这个怎么样?

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)

另见帖子:How do I modify a text file in Python?