Redirect print output to file in Python

谁都会走 提交于 2019-12-12 02:05:04

问题


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)

To output to a text file.

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()

From: How to redirect 'print' output to a file using python?


回答1:


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)

More info here



来源:https://stackoverflow.com/questions/28223774/redirect-print-output-to-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!