Python-将行写入文件的正确方法?
我已经习惯了 print >>f, "hi there"
但是,似乎print >>
已经弃用了。推荐使用哪种方法进行上述操作?
更新:关于…的所有这些答案,”\n”这是通用的还是特定于Unix
的?IE,我应该"\r\n"在Windows
上运行吗?
-
这应该很简单:
with open('somefile.txt', 'a') as the_file: the_file.write('Hello\n')
从文档:
os.linesep
写入以文本模式打开的文件时(默认),请勿用作行终止符;在所有平台上都使用一个’\ n’代替。一些有用的读物:
- with声明
- open()
- ‘a’用于追加或使用
- ‘w’截断书写
- os(特别是os.linesep)
-
你应该使用
print()
Python 2.6+起提供的功能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
引用Python文档中有关换行符的内容:
在输出中,如果换行符为
None
,则所有'\n'
写入的字符都会转换为系统默认的行分隔符os.linesep
。如果newline
是''
,则不会进行翻译。如果换行符是其他任何合法值,'\n'
则将写入的所有字符转换为给定的字符