parsing a tab-separated file in Python

io, python, tabs

Solution

You can use the `csv` module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where `line` is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the `zip()` builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

Problem

I'm trying to parse a tab-separated file in Python where a number placed k tabs apart from the beginning of a row, should be placed into the k-th array. Is there a built-in function to do this, or a better way, other than reading line by line and do all the obvious processing a naive solution would perform?

Original source

Related problems