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])
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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With