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.

Subscribe to receive more programming tricks.

We don’t spam!

Subscribe to receive more programming tricks.

We don’t spam!

0 0 votes
Article Rating
Notify of

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

1 Comment
Oldest Most Voted
Inline Feedbacks
View all comments

I Googled hours for a solution that I found here !!!
Thank You ! Thank You ! Thank You !

Would love your thoughts, please comment.x