user3435341
user3435341

Reputation: 51

How to read just lists in a text file in Python?

I need to read a text file like this

bruce
chung
[email protected]
8893243
costarricense
divisa del informe colones
['nokia', 5277100.0, 'china']
['samsung', 10554200.0, 'turkey']
['apple', 52771000.0, 'argentina']

But I need to read just the lists inside the file and assign them into a new variable.

I've used this

data =[ast.literal_eval(x) for x in open("test.txt")]
registros = data

And it worked well before until I added the information of the user below.

Is there a way to read only the lists in the text?

Upvotes: 1

Views: 109

Answers (2)

fastbreak78
fastbreak78

Reputation: 95

This should work, assuming you're not planning on using brackets for any purpose besides encapsulating lists.

import re
import ast

matches = []
data = open("test.txt", 'r').read()
for listString in re.findall(r"\[.*\]", data):
  matches.append(ast.literal_eval(listString))

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90889

You can use str.startswith() to check if the string starts with '[' , and use ast.literal_eval() only if that is true. Example -

with open("test.txt") as f:
    registros = [ast.literal_eval(x) for x in f if x.startswith('[')]

Demo -

>>> s = """bruce
... chung
... [email protected]
... 8893243
... costarricense
... divisa del informe colones
... ['nokia', 5277100.0, 'china']
... ['samsung', 10554200.0, 'turkey']
... ['apple', 52771000.0, 'argentina']""".splitlines()
>>> import ast
>>> registros = [ast.literal_eval(x) for x in s if x.startswith('[')]
>>> registros
[['nokia', 5277100.0, 'china'], ['samsung', 10554200.0, 'turkey'], ['apple', 52771000.0, 'argentina']]

For the updated requirements in the comments -

How can I also read only the user info and assign it to a variable using this method?

Assuming any line that is not a list, is part of the user info

You can use a simple for loop, keep appending to a variable if the line does not start with '[' , and if it does, use ast.literal_eval() on it, and append it to the registros list.

Example -

import ast
with open("test.txt") as f:
    user_info = ''
    registros = []
    for line in f:
        if line.startswith('['):
            registros.append(ast.literal_eval(line))
        else:
            user_info += line

If the user_info would always just be 6 lines (as given in the comments) , you can also use -

import ast
with open("test.txt") as f:
    user_info = ''
    for i,line in enumerate(f):
        user_info += line
        if  i==5:
            break
    registros = [ast.literal_eval(x) for x in f if x.startswith('[')]

Upvotes: 5

Related Questions