1

I have a text file (let's call it file.txt) of containing only 1 line of this type:

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

I want to convert that into a 2-dim array in python so that I will get

[[1 2 3]

[4 5 6]

[7 8 9]

[10 11 12]

[12 14 15]]

I tried using

with open("file.txt", "r") as f:

data = f.readlines()

c = np.array(data)

print(c)

c.dtype

But it returns me ['[1,2,3],[4,5,6],[7,8,9],[10,11,12]'] and dtype('<U34')

Can somebody help me with this?

Ps. Above is just an example. In reality I will work on arbitrary size 2-dim array

2 Answers 2

5

Use json to help you

with open("file.txt", "r") as f:
    content = "[" + f.read() + "]"

values = json.loads(content)

values_np = np.array(values)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. That's useful. I am new to coding world and new to stack overflow forum. I realized you changed the text (code) in my question. Just how did you type the code in that nice format? Sorry if this is noob question to you.
@user19532602 click on edit below your post and you'll see it, it used ` (backquote)
0

You can use eval

import numpy as np

str_array = open('file.txt', 'r').read()

arr = np.array(eval(str_array))

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.