8
votes

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 include the first column too

f = open("/tmp/data.txt")
for l in f.readlines():
  print l.strip().split("\t")
  break
  f.close()

Output: ['session_id\t', '\tevent_id_concat']

The first column name is id where it s not printed in the above array

EDIT

print l yields the following

EDIT 1:

   'id\tsession_id\tevent_id_concat\r\n'

   Output: ['id\t', '\tevent_id_concat'] 
2
It should work. Can you add print l before your print statement and show the output? P.S. Also, no need for .readlines() here, pretty much as always. - Lev Levitsky
I think csv module will do the job. - Evgeny Lazin
Can you actually show the output of print repr(l)? - poke
Yeah that's probably what I wanted :) - Lev Levitsky
'id\tsession_id\tevent_id_concat\r\n'.strip().split('\t') gives ['id', 'session_id', 'event_id_concat'] for me. Are you sure you show the actual code that's executed? - Lev Levitsky

2 Answers

18
votes

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
with open('/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
with open('/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.

7
votes

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

with open('/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.