How to redirect 'print' output to a file? How to redirect 'print' output to a file? python python

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 sysorig_stdout = sys.stdoutf = open('out.txt', 'w')sys.stdout = ffor i in range(2):    print('i = ', i)sys.stdout = orig_stdoutf.close()

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

from contextlib import redirect_stdoutwith 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.


You can redirect print with the file argument (in Python 2 there was the >> operator instead).

f = open(filename,'w')print('whatever', file=f) # Python 3.xprint >>f, 'whatever'     # Python 2.x

In most cases, you're better off just writing to the file normally.

f.write('whatever')

or, if you have several items you want to write with spaces between, like print:

f.write(' '.join(('whatever', str(var2), 'etc')))


Python 2 or Python 3 API reference:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Since file object normally contains write() method, all you need to do is to pass a file object into its argument.

Write/Overwrite to File

with open('file.txt', 'w') as f:    print('hello world', file=f)

Write/Append to File

with open('file.txt', 'a') as f:    print('hello world', file=f)