1

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?

2 Answers 2

5

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('[')]
Sign up to request clarification or add additional context in comments.

3 Comments

How can I also read only the user info and assign it to a variable using this method?
Can you be sure that its the first 6 lines? Or is it all lines before the first line with [ ?
It will be allways 6 lines
1

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))

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.