Reputation: 29
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.
Upvotes: -1
Views: 237
Reputation: 520878
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
Upvotes: 2