Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reading data file into lists or arrays

Tags:

python

file-io

For some reason, I decided to save my list of data as a string. If I use

f = open('tarfile.txt')
for line in f.readlines():
    print line
f.close()

my output looks like:

[  53.7775   13.4375   26.525    48.63    125.      185.      653.    ]    
[  53.7775    13.33625   26.73375   48.68375  125.       185.       653.     ]    
[  53.7775    13.325     27.11375   48.8875   126.       187.       653.     ]    
[  53.7775    13.43625   27.3175    48.92875  126.       187.       653.     ]    
[  53.7775    14.4825    33.07375   51.7325   141.       202.       595.     ]

I would like to read this data in to 2D array. I have searched and tried various methods such as pickle, eval, json, etc but nothing worked

like image 610
user1532056 Avatar asked Oct 23 '12 13:10

user1532056


1 Answers

If you are using numpy (or don't mind using it), you can do numpy.loadtxt('tarfile.txt', usecols=range(1,8)). It is particularly nice if you are going to want your data in a 2-d numpy array anyway.

like image 112
Alok Singhal Avatar answered Oct 05 '22 01:10

Alok Singhal