reading a specific column from file

Fredrik Lundh fredrik at pythonware.com
Fri Jan 11 07:27:53 EST 2008


cesco wrote:

> 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?

use the "split" method and plain old indexing:

for line in open("file.txt"):
     columns = line.split("\t")
     print columns[2] # indexing starts at zero

also see the "csv" module, which can read all sorts of 
comma/semicolon/tab-separated spreadsheet-style files.

> I've found quite interesting the linecache module

the "linecache" module seems to be quite popular on comp.lang.python 
these days, but it's designed for a very specific purpose (displaying 
Python code in tracebacks), and is a really lousy way to read text files 
in the general case.  please unlearn.

</F>




More information about the Python-list mailing list