Skip to content Skip to sidebar Skip to footer

Python Reading A Tab Separated File Using Delimiter

I am using the following to read a tab separated file .There are three columns in the file but the first column is being ignored when i print the column header only.how can i inclu

Solution 1:

I would also suggest to use the csv module. It is easy to use and fits best if you want to read in table like structures stored in a CSV like format (tab/space/something else delimited).

The module documentation gives good examples where the simplest usage is stated to be:

import csv
withopen('/tmp/data.txt', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

Every row is a list which is very usefull if you want to do index based manipulations.

If you want to change the delimiter there is a keyword for this but I am often fine with the predefined dialects which can also be defined via a keyword.

import csv
withopen('/tmp/data.txt', 'r') as f:
    reader = csv.reader(f, dialect='excel', delimiter='\t')
    for row in reader:
        print row

I am not sure if this will fix your problems but the use of elaborated modules will ensure you that something is wrong with your file and not your code if the error will remain.

Solution 2:

It should work but it is better to use 'with':

withopen('/tmp/data.txt') as f:
   for l in f:
       print l.strip().split("\t")

if it doesn't then probably your file doesn't have the required format.

Post a Comment for "Python Reading A Tab Separated File Using Delimiter"