在Python中将打印输出重定向到.txt文件 [英] Redirecting the print output to a .txt file in Python

查看:455
本文介绍了在Python中将打印输出重定向到.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的入门者.我已经尝试过从stackoverflow答案中解决此问题的许多方法,但是它们都不在我的脚本中起作用.
我有这个小脚本可以使用,但是我无法将庞大的结果保存到.txt文件中,因此我可以分析数据.如何将打印输出重定向到计算机上的txt文件?

I am complete beginner in Python. I have tried many methods from stackoverflow answers on this question, but neither of them works in my script.
I have this little script to use, however I can not get the huge result to .txt file so I can analyize the data. How do I redirect the print output to txt file on my computer?

from nltk.util import ngrams
import collections

with open("text.txt", "rU") as f:
    sixgrams = ngrams(f.read().decode('utf8').split(), 2)

result = collections.Counter(sixgrams)
print result
for item, count in sorted(result.iteritems()):
    if count >= 2:
        print " ".join(item).encode('utf8'), count

推荐答案

print语句支持重定向(>> fileobj):

...
with open('output.txt', 'w') as f:
    print >>f, result
    for item, count in sorted(result.iteritems()):
        if count >= 2:
            print >>f, " ".join(item).encode('utf8'), count

在Python 3.x中, print函数接受可选关键字参数file:

In Python 3.x, print function accepts optional keyword parameter file:

print("....", file=f)

如果您在Python 2.6+中执行 from __future__ import print_function ,则上述方法是即使在Python 2.x中也是可能的.

If you do from __future__ import print_function in Python 2.6+, above approach is possible even in Python 2.x.

这篇关于在Python中将打印输出重定向到.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆