0

My text file consists of a sequence of arrays all on the same line (i.e. no indentations). I'm trying to take these arrays and put them into a python list.

The text file is like this:

[1,2,3,4],[1,2,3,5],[1,2,3,6],[1,2,3,7],[1,2,3,8],[1,2,3,9],[1,2,3,10]........

I'm trying to take this and make a list of lists such as:

[[1,2,3,4],[1,2,3,5],[1,2,3,6],[1,2,3,7],[1,2,3,8],[1,2,3,9],[1,2,3,10]]

I tried using the read method but all I get is one giant string.

1
  • 1
    Can you share how you got that giant string and how it looks like. Commented Apr 18, 2015 at 22:18

1 Answer 1

1

First, read() in your file and save it to a variable (equivalent to this):

a = '[1,2,3,4],[1,2,3,5],[1,2,3,6],[1,2,3,7],[1,2,3,8],[1,2,3,9],[1,2,3,10]'

If you don't want to use eval(), you can use the safer ast.literal_eval():

import ast
list(ast.literal_eval(a))

If you don't want to use any kind of evaluation, you can use built-ins and string methods:

[list(map(int, line.split(','))) for line in a.strip('[]').split('],[')]

These will all produce the following:

[[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 3, 7], [1, 2, 3, 8], [1, 2, 3, 9], [1, 2, 3, 10]]
Sign up to request clarification or add additional context in comments.

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.