'HOW TO READ LINE FROM A TEXT FILE INTO AN 2D ARRAY IN PYTHON

So, the text file looks like this: [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]

The question is how can I read the line and make it a 2d array that has 5 rows and 3 columns? I have tried this code but this error came out "ValueError: cannot reshape array of size 1 into shape (5,3)"

file = open("test.txt", "r")
allocation = np.array(file.readline())
all = np.reshape(allocation, (5,3))
print(allocation)

file.close()

Sorry if the question has already been asked before but I don't really understand other solutions. Thank you.



Solution 1:[1]

One straightforward approach uses the eval() function:

inp = "[[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]"
arr = eval(inp)
print(arr)  # [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]
print(arr[1][1])  # 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Biegeleisen