2

In the following code:

with open("output", "w") as f:
    print >> f, "foo"
    print >> f, "bar"

The 'output' file will be:

foo
bar

How to avoid newline and white spaces using print >>?

P.S.: I'm actually wanting to know if it is possible to do it using print >>. I know other ways in which I can avoid the '\n', such as f.write("foo") and f.write("bar").

Also, I know about the trailing comma. But that prints foo bar, instead of foobar.

Enzo Nakamura
  • 127
  • 1
  • 9

1 Answers1

5

A trailing comma makes the print statement do magic, like printing no newline unless there’s no further output (not documented!):

print >>f, "foo",

but that’s not really helpful if you want a consistent no-newline policy (and because you have a second print, which will print a space). For that, use Python 3’s print function:

from __future__ import print_function

and

print("foo", end="", file=f)
Ry-
  • 218,210
  • 55
  • 464
  • 476