在Python中将打印输出重定向到文件 [英] Redirect print output to file in Python

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

问题描述

我正在尝试将打印输出重定向到Python 3.4中的文件-现在,因为它可以将我的脚本打印输出到shell中.我真的不需要它来做到这一点.这是我的代码:

I am trying to redirect print output to a file in Python 3.4 - right now as it stands my script prints to the shell. I don't really need it to do that. Here's my code:

with open('Input.txt') as namelist:
    for line in namelist:
        line_lower = line.lower()
        a = namelist.readline()
        if fuzz.ratio(a, line) >= 95:
            print(fuzz.ratio(a, line))
            print(a + ": " + line)

我真的很想要打印出以下内容:

I'd really like for what prints out as a result of this:

            print(fuzz.ratio(a, line))
            print(a + ": " + line)

要输出到文本文件.

到目前为止,我发现的内容似乎不适用于Python 3,因为print语句现在是需要括号而不是语句的函数.这是不起作用的示例:

What I found so far doesn't look like it works with Python 3, since print statements are now functions that require parentheses instead of statements. Here's an example of what isn't working:

f = open('out.txt', 'w')
print >> f, 'Filename:', filename  # or f.write('...\n')
f.close()

发件人: 如何使用python将打印"输出重定向到文件?

推荐答案

Python 3.0引入了print()函数,该函数支持可选参数file.所以你可以做类似的事情

Python 3.0 introduced the print() function that supports an optional argument, file. So you can do things like

with open("myfile.txt", "w") as f:
    print("Hello, world!", file=f)

更多信息此处

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

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