Brad Conyers
Brad Conyers

Reputation: 1251

Break multiple lines in a text file into a list of lists

I am working with a text file ex:

blahblahblahblahblahblahblah
blahblahblahblahblahblahblah
start
important1a important1b
important2a important2b
end
blahblahblahblahblahblahblah

What I want is to get an output like

["'important1a', 'important1b'", "'important2a', 'important2b'"]

Where each important line is split into individual elements, but they are grouped together by line in one list.

I have gotten close with this:

import shlex

useful = []
with open('test.txt', 'r') as myfile:
    for line in myfile:
        if "start" in line:
            break
    for line in myfile:
        if "end" in line:
            break       
        useful.append(line)

data = "".join(useful)

split_data = shlex.split(data)
print split_data

This outputs:

['important1a', 'important1b', 'important2a', 'important2b']

There is no distinction between lines.

How can I modify this to distinguish each line? Thanks!

Upvotes: 1

Views: 1024

Answers (3)

Wolph
Wolph

Reputation: 80101

How about something like this:

useful = []
for line in open('test.txt'):
    parts = line.split()
    if parts[1:]:
        useful.append("'%s'" % "', '".join(parts))

print useful

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363807

List comprehensions to the rescue:

[", ".join(map(repr, ln.split())) for ln in open("test.txt")
                                  if "important" in ln]

returns

["'important1a', 'important1b'", "'important2a', 'important2b'"]

Upvotes: 2

betabandido
betabandido

Reputation: 19704

You could use list comprehensions. Your code would look like:

useful = []
with open('test.txt', 'r') as myfile:
    for line in myfile:
        if "start" in line:
            break
    for line in myfile:
        line = line.strip()
        if "end" in line:
            break       
        useful.append(line)

print(["'%s'" % ','.join(elem.split(' ')) for elem in useful])

Upvotes: 0

Related Questions