learner
learner

Reputation: 335

writing tab separated values into a file

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])

Upvotes: 8

Views: 54790

Answers (3)

Levon
Levon

Reputation: 143047

outf.write('{0[1]}\t{0[2]}\t{0[3]}\t{0[4]}\t{0[4]}\n'.format(l))

will write the data to the file tab separated. Note that write doesn't automatically append a \n, so if you need it you'll have to supply it yourself.

Also, it's better to open the file using with:

with open('output', 'w') as outf:
   outf.write('{0[1]}\t{0[2]}\t{0[3]}\t{0[4]}\t{0[4]}\n'.format(l))

as this will automatically close your file for you when you are done or an exception is encountered.

Upvotes: 0

Makoto
Makoto

Reputation: 106410

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

Upvotes: 20

Rafe Kettler
Rafe Kettler

Reputation: 76955

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

Upvotes: 6

Related Questions