【发布时间】:2019-08-02 01:32:04
【问题描述】:
我正在编写一个待办事项列表应用程序,并存储类对象task 我正在挑选一个已创建对象的列表。但是,当我加载数据时,列表显示为空。我构造它的方式是为每个会话创建一个空列表,然后附加泡菜文件的内容。当创建新任务时,它们会被附加,然后整个列表会被附加,然后重新加载。
这是我的第一个真正的软件项目,所以我的代码看起来很粗糙。我查看了它,找不到任何明显的错误,但显然我做错了什么。
以下是相关代码:
import _pickle as pickle
import os.path
from os import path
from datetime import datetime
#checks if data exists, and creates file if it does not
if path.exists('./tasks.txt') != True:
open("./tasks.txt", 'wb')
else:
pass
#define class for tasks
class task:
def __init__(self, name, due, category):
self.name = name
self.due = datetime.strptime(due, '%B %d %Y %I:%M%p')
self.category = category
def expand(self): # returns the contents of the task
return str(self.name) + " is due in " + str((self.due - datetime.now()))
data = []
# load data to list
def load_data():
with open('tasks.txt', 'rb') as file:
while True:
data = []
try:
data.append(pickle.load(file))
except EOFError:
break
...
# returns current task list
def list_tasks():
clear()
if not data:
print("Nothing to see here.")
else:
i = 1
for task in data:
print("%s. %s" % (i, task.expand()))
i = i+1
#define function to add tasks
def addTask(name, due, category):
newTask = task(name, due, category)
data.append(newTask)
with open('./tasks.txt', 'wb') as file:
pickle.dump(data, file)
load_data()
list_tasks()
...
load_data()
list_tasks()
startup()
ask()
【问题讨论】:
-
如果删除
data = []循环中的data = []行会怎样? -
@Kevin 啊,我现在看到了问题所在。但是,我现在明白了:
Traceback (most recent call last): File "/Users/john/Developer/todo/main.py", line 77, in <module> list_tasks() File "/Users/john/Developer/todo/main.py", line 43, in list_tasks print("%s. %s" % (i, task.expand())) AttributeError: 'list' object has no attribute 'expand' -
大胆猜测,但也许将行从
data.append(pickle.load(file))更改为data.extend(pickle.load(file))会有所帮助吗?在测试之前,您可能需要删除tasks.txt文件以确保它没有结构不正确的数据。 -
@Kevin 工作!回答,我会检查标记它。非常感谢。
标签: python serialization pickle