title: reopening sys.stdout after it is closed by with statement
body: <p>I'm having trouble with a printing information that is input from a yaml file using PyYAML. I'm trying to reduce line-count, without affecting functionality. In some runs the output has to be appended to a file, in others to stdout.</p>
  
  <p>At first I used this multiple times in my function <em>processData</em>:</p>
  
  <pre><code>    if logName:
          fp = open(logName, 'a')
      else:
          fp = sys.stdout
      print(........, file=fp)
      print(........, file=fp)
      if logName:
          fp.close()
  </code></pre>
  
  <p>That worked, but has the disadvantages of not using the <em>with</em> statement when something goes wrong.</p>
  
  <p>The actual problem is not the complex print statements, but that I </p>
  
  <p>1) don't want to duplicate code when printing to file or to sys.stdout<br>
  2) want to use the <em>with</em> statement so that files get closed if there are print errors<br>
  3) there are several such blocks, I don't want to call a different function for each of them, and so preventing code duplication</p>
  
  <p>Then what I tried is:</p>
  
  <pre><code>def processData(yamlData, logName=None):
      ......
      with open(logName, 'a') if logName else sys.stdout as fp:
          print(........, file=fp)
          print(........, file=fp)
      .....
      with open(logName, 'a') if logName else sys.stdout as fp:
          print(........, file=fp)
          print(........, file=fp)
  </code></pre>
  
  <p>If there is not a logName, this errors to "ValueError: I/O operation on closed file". Any suggestions on how to get this to work without the original duplication? Can I reopen sys.stdout?</p>