1import sys
2
3print('This message will be displayed on the screen.')
4
5original_stdout = sys.stdout # Save a reference to the original standard output
6
7with open('filename.txt', 'w') as f:
8 sys.stdout = f # Change the standard output to the file we created.
9 print('This message will be written to a file.')
10 sys.stdout = original_stdout # Reset the standard output to its original value
11