簡體   English   中英

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 ,而無需使用換行符並且具有文件重定向功能,您可以使用__futures__導入python 3 print函數,並使用此函數的新參數:

from __future__ import print_function

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

參考資料:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM