如何使用Python在文本文件中写入单行?

如何使用Python在文本文件中写入单行?

您可以使用write函数将该行简单地写入文件。

更多Python相关文章,请阅读:Python 教程

例如

f = open('myfile', 'w')
f.write('hi there\n')  #python将 \n 转换为 os.linesep
f.close()  #在大多数情况下,您可以省略这一步,因为析构函数将调用它

或者,您可以使用自Python 2.6+起可用的print()函数。

from __future__ import print_function  #仅适用于Python 2
print("hi there", file=f)

对于Python 3,您无需导入,因为print()函数是默认的。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程