Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

Output: ['session_id', 'event_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:

   'idsession_idevent_id_concat
'

   Output: ['id', 'event_id_concat'] 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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='')
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...