用Python编写文件的正确方法 [英] Correct way to write line to file in Python

查看:93
本文介绍了用Python编写文件的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯做 print>> f,hi there



看来 print>> 正在被弃用。什么是建议的方式做上面的行?

更新:
关于所有这些答案与 \\\
...是通用还是Unix特有的? IE浏览器,我应该在Windows上做\r\\\

解决方案你应该使用自Python 2.6以来可用的 print()函数

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

对于Python 3,您不需要 import ,因为 print()



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

Python文档关于换行符:



< blockquote>

输出时,如果换行符是None,任何 \\\
写入被转换到系统缺省行分隔符, os.linesep 。如果换行符是'',则不会发生翻译。如果换行符是任何其他的合法值,则写入的任何'\ n'字符都会被转换为给定的字符串。



I'm used to doing print >>f, "hi there"

However, it seems that print >> is getting deprecated. What is the recommended way to do the line above?

Update: Regarding all those answers with "\n"...is this universal or Unix-specific? IE, should I be doing "\r\n" on Windows?

解决方案

You should use the print() function which is available since Python 2.6+

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

For Python 3 you don't need the import, since the print() function is the default.

The alternative would be to use:

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

Quoting from Python documentation regarding newlines:

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编写文件的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆