Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing tab separated values into a file

Tags:

python

From a file, i have taken a line, split the line into 5 columns using split(). But i have to write those columns as tab separated values in an output file.

Lets say that i have l[1], l[2], l[3], l[4], l[5]...a total of 5 entries. How can i achieve this using python? And also, i am not able to write l[1], l[2], l[3], l[4], l[5] values to an output file.

I tried both these codes, both not working(i am using python 2.6):

code 1:

with open('output', 'w'):
   print l[1], l[2], l[3], l[4], l[5] > output

code 2:

with open('output', 'w') as outf:
   outf.write(l[1], l[2], l[3], l[4], l[5])
like image 364
learner Avatar asked Jun 15 '12 17:06

learner


2 Answers

You can use a parameter in the with statement representing the file you're writing to. From there, use .write(). This assumes that everything in l is a string, otherwise you'd have to wrap all of them with str().

with open('output', 'w') as f:
    f.write(l[1] + "\t" + l[2] + "\t" + l[3] + "\t" + l[4] + "\t" + l[5] + "\n")

Alternatively, and more efficiently, you can use .join():

with open('output', 'w') as f:
    f.write('\t'.join(l[1:]) + '\n')
like image 60
Makoto Avatar answered Nov 14 '22 03:11

Makoto


The write() method takes a string as its first argument (not a variable number of strings). Try this:

outf.write(l[1] + l[2] + l[3] + l[4] + l[5])  

or better yet:

outf.write('\t'.join(l) + '\n')
like image 6
Rafe Kettler Avatar answered Nov 14 '22 03:11

Rafe Kettler