用Python编写文件的正确方法 [英] Correct way to write line to file in Python
问题描述
我习惯做 print>> f,hi there
看来 print>>
正在被弃用。什么是建议的方式做上面的行?
更新:
关于所有这些答案与 \\\
...是通用还是Unix特有的? IE浏览器,我应该在Windows上做\r\\\
?
print()
函数 from __future__ import print_function#仅用于Python 2
print(hi there,file = f)
对于Python 3,您不需要 从Python文档关于换行符: 输出时,如果换行符是None,任何 I'm used to doing However, it seems that Update:
Regarding all those answers with You should use the For Python 3 you don't need the The alternative would be to use: Quoting from Python documentation regarding newlines: On output, if newline is None, any
这篇关于用Python编写文件的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! import
,因为 print()$ c
f = open('myfile','w')
f.write('hi there\\\
')#python会将\\\
转换成os.linesep
f.close ()#你可以在大多数情况下省略,因为析构函数会调用它
< blockquote>
\\\
写入被转换到系统缺省行分隔符,
os.linesep
。如果换行符是''
,则不会发生翻译。如果换行符是任何其他的合法值,则写入的任何'\ n'
字符都会被转换为给定的字符串。
print >>f, "hi there"
print >>
is getting deprecated. What is the recommended way to do the line above?"\n"
...is this universal or Unix-specific? IE, should I be doing "\r\n"
on Windows?print()
function which is available since Python 2.6+from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)
import
, since the print()
function is the default.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
'\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.