我正在编写待办事项列表程序。它为每行保留一个文件,并让用户添加或删除项目。问题在于,由于某种原因,即使该项目被正确删除,我在文件开始时也会产生大量零字节。我会告诉你几个截图,以确保我清楚自己。用Python写入文件会插入空字节
这是在记事本++文件运行程序之前:
Normal todo list http://img683.imageshack.us/img683/2812/beforew.png
这是删除项目3(从1开始计数)之后的文件:
Item 3 is gone, but there are NUL bytes http://img190.imageshack.us/img190/9387/afterj.png
这是相关的代码。实际的程序更大,但只运行这个部分就会触发错误。
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()
请您指出错误在哪里?
非常感谢。你的答案和森林一样好,但我必须选择一个接受,所以我选择了较早的一个。与个人无关。 – Javier 2010-06-12 22:52:37