我正在編寫待辦事項列表程序。它爲每行保留一個文件,並讓用戶添加或刪除項目。問題在於,由於某種原因,即使該項目被正確刪除,我在文件開始時也會產生大量零字節。我會告訴你幾個截圖,以確保我清楚自己。用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