Search code examples
pythonpython-2.7printingfwrite

python `f.write()` and `print >>` differ by one empty line


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?


Solution

  • 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: