reading a specific column from file

Peter Otten __peter__ at web.de
Fri Jan 11 07:32:36 EST 2008


A.T.Hofkamp wrote:

> On 2008-01-11, cesco <fd.calabrese at gmail.com> wrote:
>> Hi,
>>
>> I have a file containing four columns of data separated by tabs (\t)
>> and I'd like to read a specific column from it (say the third). Is
>> there any simple way to do this in Python?
>>
>> I've found quite interesting the linecache module but unfortunately
>> that is (to my knowledge) only working on lines, not columns.
>>
>> Any suggestion?
> 
> the csv module may do what you want.

Here's an example:

>>> print open("tmp.csv").read()
alpha   beta    gamma   delta
one     two     three   for

>>> records = csv.reader(open("tmp.csv"), delimiter="\t")
>>> [record[2] for record in records]
['gamma', 'three']

Peter



More information about the Python-list mailing list