如何在Python2.x和3.x中直接打印到文本文件?
在Python2和Python3中,除了使用如何在Python2.x和3.x中直接打印到文本文件?,python,file,python-3.x,stdout,python-2.x,Python,File,Python 3.x,Stdout,Python 2.x,在Python2和Python3中,除了使用write(),还有什么方法可以写入文本文件 file = open('filename.txt', 'w') file.write('some text') 您可以使用print\u函数从python2中的python3获取print()行为: from __future__ import print_function with open('filename', 'w') as f: print('some text', file=f)
write()
,还有什么方法可以写入文本文件
file = open('filename.txt', 'w')
file.write('some text')
您可以使用
print\u函数
从python2中的python3获取print()
行为:
from __future__ import print_function
with open('filename', 'w') as f:
print('some text', file=f)
如果不希望该函数在末尾附加换行符,请将end='
关键字参数添加到print()
调用中
但是,请考虑使用<代码> f.Wrrad(“某些文本”)< /C> >,因为这更清楚,不需要<代码>“yFuturux> Supp.
”请注意,这是用换行符(<代码> \n < /代码>)打印的。end@jamylak,end='')
对于python3
将有帮助为什么您需要其他方法来实现它?一般来说,Python很少有做一件事的方法。这是有意的,也是好的。使用“打印”并不等于写,有细微的区别。
from __future__ import print_function
with open('filename', 'w') as f:
print('some text', file=f)