0

I have code with the following statement which works fine

with open(fname, 'w') as f:
    print >> f, result

Here result is not a string, but some custom object.

Now I changed it to

with open(fname, 'w') as f:
    f.write(str(result))

It basically works, but there is an extra empty line at the end. Is there a clean way to get rid of it, or even not generate it in the first place?

nos
  • 19,875
  • 27
  • 98
  • 134
  • print appends by default a newline at the end, while f.write() doesn't – GPhilo Sep 06 '17 at 14:56
  • I've posted an answer but now I'm dubious. `print` adds a newline in the end, `write` doesn't. You are saying that it's the other way round. I'm puzzled. Did you invert the snippets? – Jean-François Fabre Sep 06 '17 at 15:04
  • Here `result` is some custom object. Your answer indeed gets rid of the empty line at the end. – nos Sep 06 '17 at 15:09

1 Answers1

0

To be able, in python 2, to use print, without a newline and with file redirection, you could import python 3 print function using __futures__, and enjoy the new parameters of this function:

from __future__ import print_function

with open("U:/foo.txt","w") as f:
    print("a",end="",file=f)

references:

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219