如何直接打印到python 2.x和3.x中的文本文件?

Ash*_*ary 14 python stdout file python-2.x python-3.x

而不是使用write(),在Python 2和3中写入文本文件的另一种方式是什么?

file = open('filename.txt', 'w')
file.write('some text')
Run Code Online (Sandbox Code Playgroud)

Thi*_*ter 38

您可以使用print_function 将来的导入来获取print()python2中python3 的行为:

from __future__ import print_function
with open('filename', 'w') as f:
    print('some text', file=f)
Run Code Online (Sandbox Code Playgroud)

如果您不希望该函数在末尾附加换行符,请将该end=''关键字参数添加到该print()调用中.

但是,考虑使用,f.write('some text')因为这更清晰,不需要__future__导入.


Ash*_*ary 7

f = open('filename.txt','w')

# For Python 3 use
print('some Text', file=f)

#For Python 2 use
print >>f,'some Text'
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这会在末尾打印换行符(`\n`) (3认同)