title: How does os.path.getsize() work within a "with" block in Python?
body: <p>The <code>fun(filename)</code> function creates a new file passed to it as a parameter, adds some text and then returns its size. When <code>print(os.path.getsize(filename)</code> is used within the 'with' block it doesn't work as intended.</p>
  <pre><code>import os
  
  def fun(filename):
      with open(filename,'w') as file:
          file.write(&quot;hello&quot;)
          print(os.path.getsize(filename))
  
  fun(&quot;newFile2.txt&quot;)
  </code></pre>
  <p>It outputs <code>0</code>. But when <code>print(os.path.getsize(filename)</code> is used outside the 'with' block as</p>
  <pre><code>import os
  
  def fun(filename):
      with open(filename,'w') as file:
          file.write(&quot;hello&quot;)
      print(os.path.getsize(filename))
  
  fun(&quot;newFile2.txt&quot;)
  </code></pre>
  <p>Then it prints the correct output: <code>5</code>. What's going on behind the scenes?</p>