行をファイルに書き込む正しい方法は?

私は、print >>f, "hi there"をすることに慣れています。

しかし、print >>は廃止されつつあるようです。上の行を実行するには、どのような方法が推奨されますか?

Updateです。 IEの場合は、Windowsでも "\\" を行うべきなのでしょうか?

Python 2.6+以降で利用可能なprint()関数を使用する必要があります。

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

Python 3 では print() 関数がデフォルトなので、import は必要ありません。

代替案としては、次のようになります。

f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it

Python documentation]1から改行について引用します。

出力において、newline が None の場合、書かれた 'n' 文字はシステムのデフォルトのラインセパレータである os.linesep に変換されます。newline が '' の場合、翻訳は行われません。newline が他の合法的な値のいずれかである場合、書かれたすべての 'n' 文字は与えられた文字列に翻訳されます。

解説 (18)

私は「正しい」方法はないと思っています。

私は使います。

with open ('myfile', 'a') as f: f.write ('hi there\n')

In memoriam Tim Toady

解説 (7)

Python 3では関数になっていますが、Python 2ではソースファイルの先頭にこれを追加します。

from __future__ import print_function

そして、次のようにします。

print("hi there", file=f)
解説 (0)