Reputation: 355
I am reading lines from file in a list:
import numpy as np
lines = tuple(open('values.txt','r'))
x = np.array([line for line in lines])
values.txt
looks like:
[1,0,1,0],
[1,0,0,0]
It throws an error:
valueError: invalid literal for float()
However, if I just assign the list to x
, it works just fine.
How to take input from file in a numpy array?
Upvotes: 1
Views: 1442
Reputation: 85462
You can read the whole file at once and just add the outer []
before applying literal_eval()
to all lines:
from ast import literal_eval
with open('values.txt') as fobj:
x = np.array(literal_eval('[{}]'.format(fobj.read())))
Upvotes: 0
Reputation: 135
import numpy as np
import ast
lines = open('values.txt','r')
x = np.array([ast.literal_eval(line.strip(',\n')) for line in lines])
Upvotes: 1
Reputation: 1849
lines = open('values.txt', 'r')
x = np.array( [ map(float, (l[l.find("[")+1 : l.find("]")].split(",")))
for l in lines ] )
print x
A brief explanation:
This takes each line in your file, finds the brackets on each side, and takes the string within the brackets. We then split that string into an array using commas as the delimiter. Then, we have an array of strings so we map the float function onto each element, turning it into a floating point number. Then we use the standard list comprehension to do this to every line.
Upvotes: 1