a file contains informaton like below I'd like to covert this file into list of list of string There is a blank line between group.
pear
banana
milk
tea
coffee
and the result returns:
build_list(f):
[[pear, banana], [milk, tea, coffee]]
a file contains informaton like below I'd like to covert this file into list of list of string There is a blank line between group.
pear
banana
milk
tea
coffee
and the result returns:
build_list(f):
[[pear, banana], [milk, tea, coffee]]
Try this:
from itertools import groupby
def build_list(name):
with open(name, "r") as f:
return [[i.strip() for i in group] for key, group in
groupby(f, key=lambda k: (k.strip() == "")) if not key]
This solution will even allow for degenerate files where you have more than one empty line between groups or multiple empty lines at the end.
Stack_13328928.txt is your list. Please note that the last line in your input file has to be a new line, otherwise the last item is lost, but I think the code can be modified that you don't need a blank new line.
import csv
in_file = open("stack_13328928.txt")
CSV = csv.reader(in_file)
outer_ls = []
inter_ls = []
for i in CSV:
try:
i[0]
inter_ls += i
except:
outer_ls.append(inter_ls)
inter_ls = []
print outer_ls