Search notes:

Python: sys.stdin / sys.stdout / sys.stderr

Writing to stdout or to a file

The following example writes to a file if the script was started with an argument (sys.argv[1]) or to stdout otherwise.
import sys

if len(sys.argv) > 1:
   print("Writing to file " + sys.argv[1])

   f_ = open(sys.argv[1], 'w')

else:

   f_ = sys.stdout

f_.write('Line one\n')
f_.write('Line two\n')
f_.write('Line three')

if len(sys.argv) > 1:
   f_.close()
Github repository about-python, path: /standard-library/sys/stdout_or_file.py
The script should be called with either of the two variants:
$ python stdout_or_file.py
$ python stdout_or_file.py out.txt

See also

stdin, stdout and stderr

Index