python – How to redirect print output to a file?

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 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 theres 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 dont see it initialized.

My first guess is that glob doesnt find any bamfiles, and therefore the for loop doesnt 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.x
print >>f, whatever     # Python 2.x

In most cases, youre 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 – How to redirect print output to a file?

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)

Leave a Reply

Your email address will not be published.