将字符串写入文件的Python方式是什么?

将字符串写入文件的Python方式是什么?,python,file-io,Python,File Io,使用File.write()和print>>文件有什么区别 哪种是pythonic的文件写入方式 >>> with open('out.txt','w') as fout: ... fout.write('foo bar') ... >>> with open('out.txt', 'w') as fout: ... print>>fout, 'foo bar' ... 使用print>>文件时有什么优势吗?最具python

使用
File.write()
print>>文件
有什么区别

哪种是pythonic的文件写入方式

>>> with open('out.txt','w') as fout:
...     fout.write('foo bar')
... 

>>> with open('out.txt', 'w') as fout:
...     print>>fout, 'foo bar'
... 

使用
print>>文件时有什么优势吗?

最具python风格的方法是.write()

我甚至不知道另一种方法,但它甚至不适用于Python3.3

类似的做法是:

fout = open("out.txt", "w")
fout.write("foo bar")
#fout.close() if you were done with the writing
write()
方法写入缓冲区,每当overflown/file closed/收到显式请求(
.flush()
)时,缓冲区(缓冲区)就会刷新到文件中

print
将阻止执行,直到实际写入文件完成


首选第一种形式,因为它的执行效率更高。除此之外,第二种形式是丑陋的和非蟒蛇的。

我认为第一种形式。显式比隐式好。第二个主要是让C开发人员感到宾至如归。在python3中,第二个是
print('foo-bar',file=fout)
,但第一个保持不变。你应该看看他们做不同事情的正确解释。即使在print语句的末尾加上逗号,软空格功能也会毁了你的一天。Python 3将
print
更改为函数,因此语法不同:
print(“some string”,file=fout)