gpt4 book ai didi

python - 在 Python 中写入文件会插入空字节

转载 作者:太空狗 更新时间:2023-10-29 20:40:10 27 4
gpt4 key购买 nike

我正在编写一个待办事项列表程序。它保存一个文件,每行都有一个要做的事情,并允许用户添加或删除项目。问题是由于某种原因,我最终在文件的开头得到了很多零字节,即使该项目已被正确删除。我将向您展示几个屏幕截图,以确保我说清楚了。

这是运行程序前Notepad++中的文件:

Normal todo list

这是删除第 3 项(从 1 开始计算)后的文件:

Item 3 is gone, but there are NUL bytes

这是相关代码。实际程序更大,但仅运行这部分会触发错误。

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

能否请您指出错误在哪里?

最佳答案

在我看来,您好像忘记倒带文件流了。在 f.truncate(0) 之后,添加 f.seek(0)。否则,我认为您的下一次写入将尝试从您离开的位置开始,并在途中填充空字节。

(请注意,示例中的空字符数等于删除行中的字符数加上每个字符的回车符和换行符。)

关于python - 在 Python 中写入文件会插入空字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3030343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com