Adam K.
Adam K.

Reputation: 51

Reading file with lists to list

I have a txt file:

['aaa', 'bbb', 'ccc']
['ddd', 'eee', 'fff']

code:

with open(name.txt", 'r') as f:
    list = [line.strip() for line in f]

then I got "list":

["['aaa', 'bbb', 'ccc']", "['ddd', 'eee', 'fff']"]

and f.e. when I want to get the first element of the first list (list[0][0]) I got just character "a", not "aaa". How can I change it? Thanks.

Upvotes: 0

Views: 22

Answers (1)

unutbu
unutbu

Reputation: 880767

You could use ast.literal_eval to parse the strings into Python lists:

import ast
with open("name.txt", 'r') as f:
    data = [ast.literal_eval(line) for line in f]

then

In [148]: data
Out[148]: [['aaa', 'bbb', 'ccc'], ['ddd', 'eee', 'fff']]

In [149]: data[0][0]
Out[149]: 'aaa'

Upvotes: 1

Related Questions