reading data file into a list

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed May 2 07:33:31 EDT 2012


On 2012年5月02日 02:59:55 -0700, ArifulHossain tuhin wrote:
> I have this data file which contains raw data in newline terminated for
> like below:
>> 10.6626
> 11.2683
> 11.9244
> 12.5758
> 14.1402
> 15.1636
>> Now i want to read that file and import this data into a numpy array.
> how should i go about it?

That depends. How big is the file? Could it include extraneous whitespace 
and possibly even comments? How do you expect to deal with bad data? What 
version of Python are you using? Who will be maintaining this, a Python 
expert or somebody who doesn't know Python very well?
Here's one way (untested but should work):
import numpy
f = open("my data file.txt", "r")
contents = numpy.array([float(line) for line in f])
f.close()
-- 
Steven


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /