Context manager for a file object. If filename is present, this is the
  same as with open(filename, mode): ...

  If filename is not present, then the file object returned is either
  sys.stdin or sys.stdout depending on the mode.

  :filename: the name of the file, or None for STDIN
  :mode: the mode to open the file with

def get_file_object(filename, mode="r"):
  """Context manager for a file object. If filename is present, this is the
  same as with open(filename, mode): ...

  If filename is not present, then the file object returned is either
  sys.stdin or sys.stdout depending on the mode.

  :filename: the name of the file, or None for STDIN
  :mode: the mode to open the file with
  """
  if filename is None:
    if mode.startswith("r"):
      yield sys.stdin
    else:
      yield sys.stdout
  else:
    with open(filename, mode) as fobj:
      yield fobj