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:

import sys
sys.stdout = open('file', 'w')

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

$ python > file

Leave a Comment