110

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.
martineau
  • 119,623
  • 25
  • 170
  • 301
Clone
  • 3,378
  • 11
  • 25
  • 41

10 Answers10

196

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()
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
  • thanks for this answer. Once the first line of the code (first print) is executed, the corresponding file closes before actually executing the second print command. Right? Is there a way to print lots of stuff all together in the same file but making sure that the file closes before the second round of loop is executed? In other words, I would like to print some things in the same files for each round around the loop with closing file in between. Thanks, – Rebel May 05 '17 at 23:31
  • 13
    @Allan, you should use a `with` statement to open the file. This creates a `file` object and keeps it open throughout an entire block, then closes it at the end. Check out the first example [in this article](http://preshing.com/20110920/the-python-with-statement-by-example/). Let me know if you have any more questions! – Aaron Christiansen May 06 '17 at 07:36
  • Thank you, this works very nicely already. How could this be modified so that it's printed both in the file and the console; without evaluating the print statement only once so that time-consuming functions are only executed once? – Julian Jul 04 '19 at 07:36
  • @Julian please check the "print_both" function in this other issue https://stackoverflow.com/a/24206109/9492673 for printing both to console and in an output file – Tommaso Di Noto Jul 25 '19 at 15:21
  • Only works for Python3 – TVK Jun 03 '22 at 09:48
34

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.")
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • 11
    Is there a way to do this AND also show the text in the console? So simultaneously print to console and to a file? I would like to be able to see all my progress print statements so I know where the program is in its execution, and the troubleshooting statements, but also have all of that dump to a text file. – Korzak Jan 24 '18 at 17:57
  • 2
    @Korzak please check the "print_both" function in this other issue https://stackoverflow.com/a/24206109/9492673 for printing both to console and in an output file – Tommaso Di Noto Jul 25 '19 at 15:22
  • This one is my favorite. I simply comment out/in one line to save the results on file after verifying them with the print command. No modification required to the print command! – Abu Shoeb Jan 11 '21 at 21:06
  • To return to standard stdout print you can add `temp = sys.stdout` before `sys.stdout = open('output.txt','wt')`, and `sys.stdout = temp` after prints – dinarkino Dec 08 '21 at 10:39
  • @Korzak logging is a nice option for such a setup. The answer from gies0r could help here, also [this](https://stackoverflow.com/questions/13733552/logger-configuration-to-log-to-file-and-print-to-stdout) explanation is very clear – dinarkino Dec 08 '21 at 10:44
12

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)

S3DEV
  • 8,768
  • 3
  • 31
  • 42
8

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! :)')
gies0r
  • 4,723
  • 4
  • 39
  • 50
5

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()
vic
  • 87
  • 1
  • 5
1

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/

tripleee
  • 175,061
  • 34
  • 275
  • 318
Chandra Shekhar
  • 598
  • 1
  • 7
  • 25
1

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

Since Python 3.4 we have redirect_stdout:

import contextlib

with open('output.txt', 'w') as f, contextlib.redirect_stdout(f):
    print("Hello stackoverflow!")
    print("I have a question.")
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
0

Addding to the sys.stdout answer ; in order to make python go back to printing to the console instead of the file you would have to do:-

import sys
list = [10,20,30,40,50]

with open('output.txt', 'w') as f:
    old_stdout = sys.stdout
    sys.stdout = f
    print(list)
    sys.stdout = old_stdout

PS.: All credit to https://www.datasciencelearner.com/get-python-output-in-text-file/ - that is where i found the information. (I made this an answer because i do not have the reputation to comment to the earlier answer.)

Edit: I edited the code to use a variable to store the old value of the sys.stdout and thereafter reassign it ; rather than using sys.__stdout__ ; since the former is safer as discussed in https://stackoverflow.com/a/45200790/13603594

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/34846502) – Diego Borba Aug 18 '23 at 18:21
-3

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

print(output statement, file=open("filename", "a"))
Christian Sarofeen
  • 2,202
  • 11
  • 18
  • 2
    what did you answer different than the accepted answer already? Also, your code doesn't even work. Wrong quotation marks.. – sertsedat Mar 19 '19 at 10:59