Redirect print output to file in Python

2019-09-19 03:27发布

问题:

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