How To Print Text From Standard Output (Stdout) To File In Python

When you run print(‘ hello python ‘) in python code, it always print the text on screen, this is because python standard output is screen console. But we always want to print the text to a file instead of screen console, especially print exception error messages when exception occurred in python source code.

To fix this issue, we should first open a file object in python with write permission, then set the file object to python system standard output. Then when you invoke print(‘ text ‘) in python, the text will be printed to file. Below is the example.

import sys
from test.test_decimal import file

if __name__ == '__main__':
    
    # open a file object with write permission.
    file_object = open('./log.txt', 'w')
    
    # assign the file object to system standard output stream.
    sys.stdout = file_object
    
    # invoke print() method to print text to above file.
    print('hello python')

    # close the file object.
    sys.stdout.close()

1 thought on “How To Print Text From Standard Output (Stdout) To File In Python”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.