如何将文件行从文件追加到两个特定行之间的列表中?

时间:2017-11-10 14:18:52

标签: python

如果我有以下文本文件:

Watermelon
Carrot
Spinach
Lettuce
Tomato
Lemon

如何将CarrotTomato(包括)的行附加到空列表中?

mylist = ['Carrot','Spinach','Lettuce','Tomato']

我试过了:

mylist = []
for aline in file:
    aline = aline.rstrip('\n')
if aline.startswith('Carrot')
    mylist.append(aline)

显然只是将'Carrot'添加到列表中,但是如何让它一直追加到停止点?

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

with open('filename.txt') as f:

   file_data = [i.strip('\n') for i in f][1:-1]

更通用的解决方案:

with open('filename.txt') as f:
    s = [i.strip('\n') for i in f]
    final_data = s[s.index("Carrot"):s.index("Tomato")+1] if s.index("Carrot") < s.index("Tomato") else s[s.index("Tomato"):s.index("Carrot")+1]

答案 1 :(得分:1)

以更通用的方式,假设“胡萝卜”和“番茄”的位置都没有固定,但“胡萝卜”总是在“番茄”之前,你可以这样做:

with open('file.txt') as temp_file:
  lines = [line.rstrip() for line in temp_file]

lines[lines.index("Carrot"):lines.index("Tomato")+1]  

如果您无法分辨出哪个值(番茄或胡萝卜),您可以让Python为您解决:

with open('file.txt') as temp_file:
  lines = [line.rstrip() for line in temp_file]

carrot_idx = lines.index("Carrot")
tomato_idx = lines.index("Tomato")

lines[min(carrot_idx,tomato_idx):max(carrot_idx,tomato_idx)+1]  

答案 2 :(得分:1)

来自takewhile的{​​p> dropwhlieitertools是为此而制作的。

from itertools import takewhile, dropwhile

def from_to(filename, start, end):
    with open(filename) as f:
        stripped = (line.rstrip() for line in f)
        dropped = dropwhile(lambda line: line != start, stripped)
        taken = takewhile(lambda line: line != end, dropped)
        for item in taken:
            yield item
        yield end

使用您的文件进行演示:

>>> list(from_to('test.txt', 'Carrot', 'Tomato'))
['Carrot', 'Spinach', 'Lettuce', 'Tomato']

这种方法的优点是您不会放弃已打开文件的迭代器属性,因此对于非常大的文件不会有任何记忆问题。

相关问题