Sankarshana
Sankarshana

Reputation: 73

Input from text file (Eg: [[1,2],[3,4]]) into 2d list in python

I have an input dataset in .txt format which looks like,

[[1, 2, 3], [4, 5, 6]]


[[7, 8, 9], [10, 11, 12]]

How do I read it into a 3-d python list where the first index is the line no. such as,

list[0][0][0] = 1


list[1][1][2] = 12

Upvotes: 1

Views: 165

Answers (2)

U13-Forward
U13-Forward

Reputation: 71610

Use with open with a loop to get each line and use ast.literal_eval to get it into a list, then append it into the l_3d list:

import ast
l_3d = []
with open('file.txt', 'r') as f:
    for line in f:
        l_3d.append(ast.literal_eval(line.rstrip()))

Thanks to @khachik :-), you can do the same thing just with json.loads:

import json
l_3d = []
with open('file.txt', 'r') as f:
    for line in f:
        l_3d.append(json.loads(line.rstrip()))

And now in both cases:

print(l_3d)

Is:

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

Upvotes: 2

Tom.chen.kang
Tom.chen.kang

Reputation: 183

import numpy as np
import json
with open('test.txt', 'r') as f:
    data = f.read()
datalist = data.split('\n')
blank = []
for i in range(len(datalist)):
    blank.append(json.loads(datalist[i]))
blank[1][1][1]

Upvotes: 0

Related Questions