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
Use json
to help you
with open("file.txt", "r") as f:
content = "[" + f.read() + "]"
values = json.loads(content)
values_np = np.array(values)
You can use eval
import numpy as np
str_array = open('file.txt', 'r').read()
arr = np.array(eval(str_array))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.