title: How to redirect print command output either to a file or to screen based on an if statement condition in Python?
body: <p>I have a simple code that prints a string. I'd like to implement an if condition that if the value was true it will print the string to a file, otherwise it will print it to screen.</p>
  <p>Is there any way to do this without having 2 identical print commands (one to print to file and another one to display)?
  Something similar to the below snippet:</p>
  <pre><code>filename = 'log.txt'
  if SomeCondition == TRUE:
      with open(filename, 'a') as f:
          print(&quot;Hello World!&quot;, file=f)
  else:
      print(&quot;Hello World!&quot;) #Is there a way to avoid duplicating the print statment?
  </code></pre>
  <p>Appreciate your help!</p>