-1

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.

4
  • what other solutions don't you understand? Commented May 18, 2022 at 16:13
  • 1
    Take a look at the np.loadtxt function Commented May 18, 2022 at 16:13
  • Either intentionally or coincidentally, but that file is a JSON, and you could load it with json.load(). Commented May 18, 2022 at 16:15
  • Since no one but use has a that file, your example should hardcode the value returned by file.readline() Commented May 18, 2022 at 16:20

1 Answer 1

2

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