我有一个函数,我想用它来删除名为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)
答案 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)