如何将文件中的文本行附加到两行之间的列表中?

2024-06-16 13:12:50 发布

您现在位置: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',但是我怎么能让它一直加到停止点呢


Tags: in列表foriffilelemon文本文件lettuce
3条回答

来自itertoolstakewhiledropwhlie就是为了这个

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']

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

你可以试试这个:

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]

更一般地说,假设“Carrot”和“Tomato”的位置都不是固定的,但是“Carrot”总是在“Tomato”之前,您可以这样做:

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]  

相关问题 更多 >