【问题标题】:how to print directly to a text file in both python 2.x and 3.x?如何在 python 2.x 和 3.x 中直接打印到文本文件?
【发布时间】:2012-05-13 19:33:30
【问题描述】:

除了使用write(),在 Python 2 和 3 中写入文本文件的其他方法是什么?

file = open('filename.txt', 'w')
file.write('some text')

【问题讨论】:

  • 您为什么想要其他方式来做到这一点?一般来说,Python 做一件事的方法很少。这是故意的,而且很好。使用“打印”不等于写,有细微差别。

标签: python file python-3.x stdout python-2.x


【解决方案1】:

您可以使用print_function future import 在python2 中从python3 获取print() 行为:

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

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

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

【讨论】:

    【解决方案2】:
    f = open('filename.txt','w')
    
    # For Python 3 use
    print('some Text', file=f)
    
    #For Python 2 use
    print >>f,'some Text'
    

    【讨论】:

    • 请注意,这会在最后打印一个换行符 (\n)
    • @jamylak , end='') for Python 3 会有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    相关资源
    最近更新 更多