我有一个文本文件,看起来像:
[START]
hey there
how are you
[END]
[START]
i am great
long time no see
[END]
[START]
yeah
busy lives
[END]
如果我想将分隔符[START]和[END]之间的所有行追加到列表中,我该怎么做?
我试过这样做:
f = open(filename)
f.readline()
lst = []
while not (line == '[START]'):
lst.append(line)
return lst
f = open("file.txt")
line = f.readline()
lst = []
while line:
if not ('[START]' in line or '[END]' in line):
lst.append(line)
line = f.readline()
return lst
你可以用line.replace(“/ n”,“”)替换/ n或[START]或[END]
这可以通过列表理解来完成:
with open(filename) as file:
return [line.rstrip('\n') for line in file if line.startswith('[START]') or line.startswith('[END]')]