Redirect stdout to a file in Python?

If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick:

# for python3
import sys
with open(‘file’, ‘w’) as sys.stdout:
    print('test')

A far more common method is to use shell redirection when executing (same on Windows and Linux):

$ python3 foo.py > file

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)