title: Strip blank lines from a text file
body: <p>I'm trying to remove blank lines from a text file, so if I have for example:</p>
  
  <pre><code>line 1
  line 2
  
  line 3
  
  
  line 4
  line 5
  </code></pre>
  
  <p>The result after processing the file should look like this:</p>
  
  <pre><code>line 1
  line 2
  line 3
  line 4
  line 5
  </code></pre>
  
  <p>I searched stack overflow and this is what I came out with so far:</p>
  
  <pre><code>with open('file.txt', 'r+', encoding='utf-8') as file:
      for line in file:
          if line.strip():
              file.write(line)
  </code></pre>
  
  <p>This worked perfectly except for one little inconvenient; instead of replacing the original content with the new one, the result is appended to the end of the file like so:</p>
  
  <pre><code>line 1
  line 2
  
  line 3
  
  
  line 4
  line 5line 1
  line 2
  line 3
  line 4
  line 5
  </code></pre>
  
  <p>My question is, is there any way I can fix this issue inside the for loop without external storage (storing the result in a file or list and writing it back to the file)? or if there is a better way please share.</p>
  
  <p>I hope my question was clear and thanks.</p>