简体   繁体   English

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

[英]How can I append lines of text from a file to a list in between two specific lines?

If I have a text file of the following: 如果我有以下文本文件:

Watermelon
Carrot
Spinach
Lettuce
Tomato
Lemon

How would I append the lines from Carrot to Tomato (inclusive) into an empty list? 如何将CarrotTomato (包括)的行追加到空列表中?

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

I've tried: 我试过了:

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

Which obviously just appends 'Carrot' to the list but how can I make it keep appending till the stop point? 这显然只是将'Carrot'添加到列表中但是如何让它继续追加到停止点?

You can try this: 你可以试试这个:

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

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

A more generic solution: 更通用的解决方案:

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]

In a more generic way, assuming that both the location of "Carrot" and "Tomato" is not fixed, but "Carrot" will always come before "Tomato", you can do something like this: 以更通用的方式,假设“胡萝卜”和“番茄”的位置都没有固定,但“胡萝卜”总是在“番茄”之前,你可以这样做:

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

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

In case you could not tell which value comes first (Tomato or Carrot), you can let Python figure it out for you: 如果您无法分辨出哪个值(番茄或胡萝卜),您可以让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]  

takewhile and dropwhlie from itertools are made for that. 来自itertools takewhiledropwhlie就是为此而做的。

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

Demo with your file: 使用您的文件演示:

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

This approach has the advantage that you don't give up the iterator properties of an opened file, so there will be no memoery problems with very large files. 这种方法的优点是您不会放弃打开文件的迭代器属性,因此非常大的文件不会出现任何记忆问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对于具有特定类别的行数的文本文件,如何将这些行之间的行附加到列表中? - 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? 在文本文件的两个特定行(关键字)之间打印多行 - Print multiple lines between two specific lines (keywords) from a text file 如何在python中选择文本文件的特定行? - How can I get select specific lines of a text file in python? 如何使用python3从文本文件中提取两行之间的行? - How to extract lines between two lines from a text file with python3? Append 行从文本文件到 python 中的列表,不带 '\n' - Append lines from a text file to a list in python without '\n' 如何使用Python将文本文件中的某些文本行放入列表中? - How can I put certain lines of text from a text file into a list with Python? 如何从文本文件中删除特定行? - How to remove specific lines from a text file? 如何从文件的所有行中提取部分文本? - How can I extract a portion of text from all lines of a file? 解析文本文件,仅捕获具有特定字符的两行之间的行 - Parse text file and only capture lines between two lines with specific characters 从文本文件中提取两行之间的数据 - Extract data between two lines from text file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM