title: How to handle both `with open(...)` and `sys.stdout` nicely?
body: <p>Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet:</p>
  
  <pre><code>if target:
      with open(target, 'w') as h:
          h.write(content)
  else:
      sys.stdout.write(content)
  </code></pre>
  
  <p>I would like to rewrite it and handle both targets uniformly.</p>
  
  <p>In ideal case it would be:</p>
  
  <pre><code>with open(target, 'w') as h:
      h.write(content)
  </code></pre>
  
  <p>but this will not work well because sys.stdout is be closed when leaving <code>with</code> block and I don't want that. I neither want to</p>
  
  <pre><code>stdout = open(target, 'w')
  ...
  </code></pre>
  
  <p>because I would need to remember to restore original stdout.</p>
  
  <p><strong>Related:</strong></p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python">Redirect stdout to a file in Python?</a></li>
  <li><a href="http://wiki.python.org/moin/HandlingExceptions" rel="noreferrer">Handling Exceptions</a> - interesting article about handling exceptions in Python, as compared to C++</li>
  </ul>
  
  <p><strong>Edit</strong></p>
  
  <p>I know that I can wrap <code>target</code>, define separate function or use <a href="http://docs.python.org/2/library/contextlib.html#contextlib.contextmanager" rel="noreferrer">context manager</a>. I look for a simple, elegant, idiomatic solution fitting that wouldn't require more than 5 lines</p>