Ryan Smith
Ryan Smith

Reputation: 709

Convert text file of arrays into a Python list

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.

Upvotes: 0

Views: 88

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49320

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

Upvotes: 1

Related Questions