0

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]]
1
  • I am thinking about geting rid of the blank line between each group. But so far my code is not working. Commented Nov 11, 2012 at 5:57

3 Answers 3

2

This should do it:

with open("data.txt") as f:
    res = [line.split('\n') for line in f.read().split('\n\n')]

Split the input data into groups then split each group into lines.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.