您可以使用write函数简单地将行写入文件。
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另外,您也可以使用print()Python 2.6+起提供的功能
from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)对于Python 3,您不需要导入,因为print()函数是默认设置。