Skip to content

Instantly share code, notes, and snippets.

@sailfish009
Created December 2, 2020 14:39
Show Gist options
  • Save sailfish009/be938d52224bfe2330fc444eafe96877 to your computer and use it in GitHub Desktop.
Save sailfish009/be938d52224bfe2330fc444eafe96877 to your computer and use it in GitHub Desktop.
Writing to a File with Python's print() Function
# https://stackabuse.com/writing-to-a-file-with-pythons-print-function/
import sys
print('This message will be displayed on the screen.')
original_stdout = sys.stdout # Save a reference to the original standard output
with open('filename.txt', 'w') as f:
sys.stdout = f # Change the standard output to the file we created.
print('This message will be written to a file.')
sys.stdout = original_stdout # Reset the standard output to its original value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment