Writing to a file in Python inserts null bytes

Posted by Javier Badia on Stack Overflow See other posts from Stack Overflow or by Javier Badia
Published on 2010-06-12T22:32:19Z Indexed on 2010/06/12 22:42 UTC
Read the original article Hit count: 410

Filed under:
|
|

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.

This is the file in Notepad++ before running the program:

Normal todo list

This is the file after deleting item 3 (counting from 1):

Item 3 is gone, but there are NUL bytes

This is the relevant code. The actual program is bigger, but running just this part triggers the error.

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()

Could you please point out where's the mistake?

© Stack Overflow or respective owner

Related posts about python

Related posts about file