Directing print output to a .txt file

PythonPython 3.x

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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 - Python

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! :)')

Solution 4 - Python

Another method without having to update your Python code at all, would be to redirect via the console.

Basically, have your Python script print() as usual, then call the script from the command line and use command line redirection. Like this:

$ python ./myscript.py > output.txt

Your output.txt file will now contain all output from your Python script.

Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .\myscript.py)

Solution 5 - Python

Another Variation can be... Be sure to close the file afterwards

import sys
file = open('output.txt', 'a')
sys.stdout = file

print("Hello stackoverflow!") 
print("I have a question.")

file.close()

Solution 6 - Python

Suppose my input file is "input.txt" and output file is "output.txt".

Let's consider the input file has details to read:

5
1 2 3 4 5

Code:

import sys

sys.stdin = open("input", "r")
sys.stdout = open("output", "w")

print("Reading from input File : ")
n = int(input())
print("Value of n is :", n)

arr = list(map(int, input().split()))
print(arr)

So this will read from input file and output will be displayed in output file.

For more details please see https://www.geeksforgeeks.org/inputoutput-external-file-cc-java-python-competitive-programming/

Solution 7 - Python

Be sure to import sys module. print whatever you want to write and want to save. In the sys module, we have stdout, which takes the output and stores it. Then close the sys.stdout . This will save the output.

import sys
print("Hello stackoverflow!" \
      "I have a question.")

sys.stdout = open("/home/scilab/Desktop/test.txt", "a")
sys.stdout.close()

Solution 8 - Python

One can directly append the returned output of a function to a file.

print(output statement, file=open("filename", "a"))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCloneView Question on Stackoverflow
Solution 1 - PythonAaron ChristiansenView Answer on Stackoverflow
Solution 2 - PythonRoman BronshteinView Answer on Stackoverflow
Solution 3 - Pythongies0rView Answer on Stackoverflow
Solution 4 - PythonS3DEVView Answer on Stackoverflow
Solution 5 - PythonvicView Answer on Stackoverflow
Solution 6 - PythonChandra ShekharView Answer on Stackoverflow
Solution 7 - PythonRanjan Kumar SahuView Answer on Stackoverflow
Solution 8 - PythonAsiis PradhanView Answer on Stackoverflow