![](/img/trans.png)
[英]How can I append lines of text from a file to a list in between two specific lines?
[英]For a text file that has some number of lines for a particular category, how do I append those in-between lines to a list?
我有一個文本文件,看起來像:
[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]')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.