猿问

正确的方式写行到文件?

正确的方式写行到文件?

我习惯了print >>f, "hi there"

然而,似乎print >>越来越不受欢迎了。什么是建议的方法来做上面的线?

更新*关于所有这些答复"\n".这是通用的还是Unix特有的?呃,我该怎么做?"\r\n"在Windows上?


温温酱
浏览 478回答 4
4回答

小怪兽爱吃肉

您应该使用print()函数,该函数可从Python2.6+开始使用。from __future__ import print_function  # Only needed for Python 2print("hi there", file=f)对于Python 3,您不需要import,因为print()函数是默认的。另一种办法是使用:f = open('myfile', 'w')f.write('hi there\n')  # python will convert \n to os.linesepf.close()   # you can omit in most cases as the destructor will call it引用自Python文档关于新线路:在输出时,如果换行符为None,则为任意'\n'写入的字符被转换为系统默认行分隔符,os.linesep..如果换行符是''没有翻译。如果换行符是任何其他合法值,则'\n'所写的字符被翻译成给定的字符串。
随时随地看视频慕课网APP

相关分类

Python
我要回答