如何在python 2.x和3.x中直接打印到文本文件? [英] how to print directly to a text file in both python 2.x and 3.x?
本文介绍了如何在python 2.x和3.x中直接打印到文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
除了使用write()
之外,在Python 2和3中写入文本文件的另一种方式是什么?
Instead of using write()
, what are the other way to write to a text file in Python 2 and 3?
file = open('filename.txt', 'w')
file.write('some text')
推荐答案
您可以使用print_function
future import 以从python2中的python3获取print()
行为:
from __future__ import print_function
with open('filename', 'w') as f:
print('some text', file=f)
如果您不希望该函数在末尾添加换行符,请在print()
调用中添加end=''
关键字参数.
If you do not want that function to append a linebreak at the end, add the end=''
keyword argument to the print()
call.
但是,请考虑使用f.write('some text')
,因为这更加清晰并且不需要__future__
导入.
However, consider using f.write('some text')
as this is much clearer and does not require a __future__
import.
这篇关于如何在python 2.x和3.x中直接打印到文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文