Directing Print Output to a .Txt File

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

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.

Redirecting function output to text file

Someone has already shared the link to the top answer on redirecting stdout but you haven't picked up on the part in that answer that might help.

from contextlib import redirect_stdout

with open('log.txt', 'w') as f:
with redirect_stdout(f):
my_function() #Call your function here any prints will go to the file
print("This text") #This will be output to the file too

This will temporarily redirect the output of print to the log.txt file.

Redirect C output to a txt file

The user input is stdin but you are redirecting only stdout to file. Hence you will see in the output.txt only what your program prints to stdout. If you want to print entered values, you have to print them after scanf.

In the example below, you should see also input values in your output.txt

printf("Enter float1: ");
scanf("%f", &float1);
printf("%f\n", float1);

How to add my print content into a text file

You can use the file argument of print:

fh = open("Price&Title", "w")
print(title, file=fh)
print(price, file=fh)
fh.close()

Redirecting the print output to a .txt file in Python

print statement in Python 2.x support redirection (>> fileobj):

...
with open('output.txt', 'w') as f:
print >>f, result
for item, count in sorted(result.iteritems()):
if count >= 2:
print >>f, " ".join(item).encode('utf8'), count

In Python 3.x, print function accepts optional keyword parameter file:

print("....", file=f)

If you do from __future__ import print_function in Python 2.6+, above approach is possible even in Python 2.x.



Related Topics



Leave a reply



Submit