-3

I'm printing my output in a file with this command:

print >> outfile, columns2[0],"\t",columns2[1],"\t",columns2[2]

My problem is that I have a "space" at the end of the content of each column.

I know some times it can be solved with sep:

print('foo', 'bar', sep='')

But I don't know how implement sep while writing in a file with my above command:

print >> outfile
smci
  • 32,567
  • 20
  • 113
  • 146
Pol
  • 9
  • 2
  • 1
    Why don't you `write` to the file? –  Nov 24 '16 at 13:57
  • I think he is talking about the space inserted at each comma, not the NL. – totoro Nov 24 '16 at 15:18
  • Are you asking about Python 3 or 2? If Python 3, this could be closed-as-duplicate of [python syntax help sep=“”, '\t'](http://stackoverflow.com/questions/22116482/python-syntax-help-sep-t) – smci Nov 24 '16 at 16:32

3 Answers3

2

The space comes from using the commas in print (Python 2.7 ?).

print >> outfile, '\t'.join(columns2)

Should resolve that issue.

totoro
  • 2,469
  • 2
  • 19
  • 23
0

The print() function can be used to print to any file, not just sys.stdout. Try:

from __future__ import print_function

print(*columns2, sep="\t", file=outfile)

From the documentation on print():

print(*objects, sep=' ', end='\n', file=sys.stdout)

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

You can use file write method, using write method won't have the extra newline at the end. Recommend to use string join method over + operator as well

outfile.write('\t'.join(column2))
# add + '\n' if need the new line
# use column2[:2] if you have more items in list and only need slice of them
Skycc
  • 3,496
  • 1
  • 12
  • 18
  • Your join command is very interesting, but I obtain the following error: "name 'join' is not defined" – Pol Nov 24 '16 at 15:27
  • Should not have the error, i have tested working, make sure you have exactly `'\t'.join` , double check `'\t'.` before the join – Skycc Nov 24 '16 at 15:41