在Python中将打印输出重定向到文件 [英] Redirect print output to file in 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 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屋!