about Grigoris Maravelias
Reading columns from a text file – fast and easy!

Reading columns from a text file – fast and easy!

Although the are many information on how to use the genfromtxt (from numpy) there is not a clear demonstration (that I found…) to show how to easily read a text file with columns of data (including strings – it is straightforward to read columns of numbers with loadtxt for example).

Suppose that we have the following text file (named ‘input.txt’):

#object	q1	q2
id-001	120.	2212.
id-002	145.	1222.
id-222	123.	1142.

Then we can just use:

g = genfromtxt('input.txt',dtype=None,names=True)

This will read all the file. dtype=None means that the command will decide what type of data is each element and name=True means that we can use the names from the first raw (header) to call each column, i.e.:

print g['object']
print g['q2']

will print:

['id-001' 'id-002' 'id-222']
[ 2212. 1222. 1142.]

That easy, that fast !

Leave a Reply

Your email address will not be published. Required fields are marked *