title: Writing to a file in Python inserts null bytes
body: <p>I'm writing a todo list program. It keeps a file with a thing to do per line, and lets the user add or delete items. The problem is that for some reason, I end up with a lot of zero bytes at the start of the file, even though the item is correctly deleted. I'll show you a couple of screenshots to make sure I'm making myself clear.</p>
  
  <p>This is the file in Notepad++ before running the program:</p>
  
  <p><a href="https://i.stack.imgur.com/OqAg5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OqAg5.png" alt="Normal todo list"></a>
  </p>
  
  <p>This is the file after deleting item 3 (counting from 1):</p>
  
  <p><a href="https://i.stack.imgur.com/vQUDF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vQUDF.png" alt="Item 3 is gone, but there are NUL bytes"></a>
  </p>
  
  <p>This is the relevant code. The actual program is bigger, but running just this part triggers the error.</p>
  
  <pre><code>import os
  TODO_FILE = r"E:\javi\code\Python\todo-list\src\todo.txt"
  
  def del_elems(f, delete):
      """Takes an open file and either a number or a list of numbers, and deletes the
      lines corresponding to those numbers (counting from 1)."""
      if isinstance(delete, int):
          delete = [delete]
      lines = f.readlines()
      f.truncate(0)
      counter = 1
      for line in lines:
          if counter not in delete:
              f.write(line)
          counter += 1
  
  f = open(TODO_FILE, "r+")
  del_elems(f, 3)
  f.close()
  </code></pre>
  
  <p>Could you please point out where's the mistake?</p>