How to Redirect 'Print' Output to a File

How to redirect 'print' output to a file?

The most obvious way to do this would be to print to a file object:

with open('out.txt', 'w') as f:
print('Filename:', filename, file=f) # Python 3.x
print >> f, 'Filename:', filename # Python 2.x

However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:

import sys

orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f

for i in range(2):
print('i = ', i)

sys.stdout = orig_stdout
f.close()

Since Python 3.4 there's a simple context manager available to do this in the standard library:

from contextlib import redirect_stdout

with open('out.txt', 'w') as f:
with redirect_stdout(f):
print('data')

Redirecting externally from the shell itself is another option, and often preferable:

./script.py > out.txt

Other questions:

What is the first filename in your script? I don't see it initialized.

My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.

Also, use os.path.join and os.path.basename to manipulate paths and filenames.

Directing print output to a .txt file

Give print a file keyword argument, where the value of the argument is a file stream. The best practice is to open the file with the open function using a with block, which will ensure that the file gets closed for you at the end of the block:

with open("output.txt", "a") as f:
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)

From the Python documentation about print:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

And the documentation for open:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead at the beginning of the with block, use "w".


The with block is useful because, otherwise, you'd need to remember to close the file yourself like this:

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()

Python, redirect some output to file from shell

The simplest solution is to make the stuff you want to go to the shell go to stderr, not stdout (the default target for print):

#!/usr/local/bin/python3.9

import sys

print("Writing to file...", file=sys.stderr) # prints to console because stderr not redirected
print({"test": 1}) # writes to output.json because stdout is redirected

The user could independently redirect stderr if they like, but the example command would leave it going to the terminal. This is typically how programs split up "debug output" from "productive output" when not explicitly writing "productive output" to a specific file.

Redirect stdout to a file in Python?

If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick:

# for python3
import sys
with open('file', 'w') as sys.stdout:
print('test')

A far more common method is to use shell redirection when executing (same on Windows and Linux):

$ python3 foo.py > file

Python: How to redirect print output to txt file?

You can do that by using providing file proxy in the file parameter of print function.

For example,

f = open('temp.txt' , 'w')
print('a' , file = f)
f.close()

Here,I redirected string 'a' in the file 'temp.txt'.

How to redirect print command output either to a file or to screen based on an if statement condition in Python?

Use this:

filename = 'log.txt'
with open(filename, 'a') as f:
print("Hello World!", file=[None, f][condition])

Python redirect print output to file over loop

Not sure whether you are using Python 2 or Python 3. Either way, the fact that you see a SyntaxError suggests that an interactive interpreter session is being used.

I am going to assume that you are using Python 2. print >> expression, expression is a valid print statement in Python 2, and your usage of it in your code is correct. It simply means to redirect the string value of the second expression in the print statement to the file-like object given in the first expression. This statement is not available in Python 3.

Probably you are pasting the code into an interactive Python session, and if so you will need to add an extra new line to "close" the previous for loop before executing the close(), otherwise you will get a SyntaxError.

It will work if you add that code to a Python 2 script file and run it:

$ python2 somefile.py

or simply make sure to enter an extra new line if using the interactive interpreter.

For Python 3 you would do this:

print('{}'.format(product), file=f)

You can also use the same print() function in Python 2 by importing it from the __future__ module:

from __future__ import print_function

In both cases you should use the with statement as you mention in your question.



Related Topics



Leave a reply



Submit