130

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. 

9 Answers 9

223

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() 
Sign up to request clarification or add additional context in comments.

5 Comments

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,
@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. Let me know if you have any more questions!
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 please check the "print_both" function in this other issue stackoverflow.com/a/24206109/9492673 for printing both to console and in an output file
Only works for Python3
42

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.") 

6 Comments

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 please check the "print_both" function in this other issue stackoverflow.com/a/24206109/9492673 for printing both to console and in an output file
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!
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
@Korzak logging is a nice option for such a setup. The answer from gies0r could help here, also this explanation is very clear
|
16

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

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.

As usual, use >> to append the output file, as > will truncate the output and start over again.

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

2 Comments

This is Linux only. While I love linux, some people just use Windoze — and I'm perfectly fine with that as long as it doesn't affect me.
I would also recommend the tee command in linux, which prints to screen AND file simultaneously. This is python agnostic and applies for anything that prints to screen.
9

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

Comments

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

Comments

2

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.") 

Comments

2

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 # Save a reference to sys.stdout file object stdout = sys.stdout print("Hello stackoverflow!" \ "I have a question.") file = open("/home/scilab/Desktop/test.txt", "a") sys.stdout = file # main code ... # Restore stdout to the sys.stdout file object you saved # This prevents stdout from erroring out on a closed file # object sys.stdout = stdout # Don't close stdout directly file.close() 

Comments

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/

Comments

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

2 Comments

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
This was already posted here. list overwrites a builtin.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.