[英]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?
[英]How can I append lines of text from a file to a list in between two specific lines?
如果我有以下文本文件:
Watermelon
Carrot
Spinach
Lettuce
Tomato
Lemon
如何將Carrot
到Tomato
(包括)的行追加到空列表中?
mylist = ['Carrot','Spinach','Lettuce','Tomato']
我試過了:
mylist = []
for aline in file:
aline = aline.rstrip('\n')
if aline.startswith('Carrot')
mylist.append(aline)
這顯然只是將'Carrot'
添加到列表中但是如何讓它繼續追加到停止點?
你可以試試這個:
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]
以更通用的方式,假設“胡蘿卜”和“番茄”的位置都沒有固定,但“胡蘿卜”總是在“番茄”之前,你可以這樣做:
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]
來自itertools
takewhile
和dropwhlie
就是為此而做的。
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']
這種方法的優點是您不會放棄打開文件的迭代器屬性,因此非常大的文件不會出現任何記憶問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.