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?
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?
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:
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.