It is good practice to use the 'with' keyword when dealing with file
objects. This has the advantage that the file is properly closed after
its suite finishes, even if an exception is raised on the way. It is
also much shorter than writing equivalent try-finally blocks.
from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)
对于Python 3,您不需要import,因为print()函数是默认的。
另一种方法是:
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
On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.
python docs建议这样做:
所以我通常就是这样做的:)
来自docs.python.org的语句:
这应该简单到:
从文档中:
一些有用的阅读:
您应该使用Python 2.6+之后提供的
print()
函数对于Python 3,您不需要
import
,因为print()
函数是默认的。另一种方法是:
引用Python documentation中有关换行符的内容:
相关问题 更多 >
编程相关推荐