1

I have a text file that is formatted as a python list ( [[1,2,3],[4,5,6]] ) and I would like to read it in python as a list

what could I use to accomplish this?

JSON was recommended to me, but I can't seem to parse the syntax. Is there a better/easier/python-ier way?

2
  • Why not json.loads(data)? Commented Apr 19, 2016 at 15:50
  • Yeah, that seems correct Farhan.K Commented Apr 19, 2016 at 15:53

1 Answer 1

4

You can use ast.literal_eval to do this

>>> import ast
>>> my_list = ast.literal_eval("[[1, 2, 3],[4, 5, 6]]")
>>> print(my_list)
[[1, 2, 3], [4, 5, 6]]
>>> print(type(my_list))
<class 'list'>
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what I needed! Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.