Issue
Is there a way to save all of the print output to a txt file in python? Lets say I have the these two lines in my code and I want to save the print output to a file named output.txt
.
print ("Hello stackoverflow!")
print ("I have a question.")
I want the output.txt
file to to contain
Hello stackoverflow!
I have a question.
Solution
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()
Answered By - Aaron Christiansen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.