python `f.write()` 和 `print >>` 相差一个空行

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

我有包含以下语句的代码,它工作正常

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

这里result不是字符串,而是一些自定义对象。

现在我改成了

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

基本可以,就是最后多了一个空行。有没有一种干净的方法来摆脱它,甚至一开始就不生成它?

为了能够在 python 2 中使用 print,没有换行符和文件重定向,您可以导入 python 3 print 函数使用 __futures__,享受这个函数的新参数:

from __future__ import print_function

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

参考文献:

  • Python 3 operator >> to print to file
  • How to print without newline or space?