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 awrite(string)
method; if it is not present orNone
,sys.stdout
will be used.
And the documentation for open
:
Open
file
and return a corresponding file object. If the file cannot be opened, anOSError
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
Screenshot of Inactive Window Printwindow + Win32Gui
Python: Sorting Items from Top Left to Bottom Right with Opencv
Command Executed with Paramiko Does Not Produce Any Output
How to Convert a Password into Asterisks While It Is Being Entered
How to Break a Line of Chained Methods in Python
How to Create a Spinning Command Line Cursor
Why Is the Empty Dictionary a Dangerous Default Value in Python
Python Selenium: Wait Until Element Is Clickable - Not Working
How to Use 'Cv2.Findcontours' in Different Opencv Versions
How to Fix "Importerror: Dll Load Failed" While Importing Win32Api
Factorize a Column of Strings in Pandas
Convert a 1D Array to a 2D Array in Numpy
Importerror: No Module Named 'Bottle' - Pycharm
Matplotlib: How to Draw a Rectangle on Image