Directing print output to a .txt file
Solution 1:
Give print
a file
keyword argument, where the value of the argument is a file stream. We can create a file stream using the open
function:
print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))
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, use "w"
.
Opening a file with open
many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print
's file
option. You must remember to close the file afterwards!
f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()
There's also a syntactic shortcut for this, which is the with
block. This will close your file at the end of the block for you:
with open("output.txt", "a") as f:
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
Solution 2:
You can redirect stdout into a file "output.txt":
import sys
sys.stdout = open('output.txt','wt')
print ("Hello stackoverflow!")
print ("I have a question.")
Solution 3:
Use the logging module
def init_logging():
rootLogger = logging.getLogger('my_logger')
LOG_DIR = os.getcwd() + '/' + 'logs'
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
rootLogger.addHandler(consoleHandler)
return rootLogger
Get the logger:
logger = init_logging()
And start logging/output(ing):
logger.debug('Hi! :)')