1 回答
TA贡献1842条经验 获得超12个赞
更新文件时,更安全的方法是创建一个临时文件,您可以在其中写入内容,同时保持原始文件的安全和不受影响。然后,写入过程完成后,您可以删除原始文件并重命名临时文件。
另外,我认为您应该有某种唯一 ID 来标识每个任务。我不得不使用行号来识别它们,但如果包含一些不可变的 ID 会更好。
最后,我建议您在获取任务时使用字典而不是列表。它允许您更轻松地访问和更新字段。
(在下面的例子中,我没有包括所有的菜单选项,我只包括了用户名编辑来说明它应该如何工作)
import os
from pprint import pprint
# The view_mine function should receive the username as a parameter
def view_mine(username):
tasks = []
i = 0
with open('tasks.txt') as f:
lines = f.read().splitlines()
for db_row, line in enumerate(lines):
assigned_to, *rest = line.split(', ')
if username == assigned_to:
# use a dictionary to easily refer to the taks' fields
data = {k: v for k, v in zip(
('number', 'db_row', 'assigned_to', 'title', 'description',
'due_date', 'date_assigned', 'completed'),
(i + 1, db_row, assigned_to, *rest))}
tasks.append(data)
i += 1
# You can customize what you want to print, I just used pprint as a shortcut for this example
pprint(tasks)
task_num = int(input("Please select Task Number you would like to edit: "))
# Get specific task at given index
task = tasks[task_num - 1]
edit_option = input('''Would you like to:
e - edit task
c - mark complete
-1- return to main menu\n''')
if edit_option == 'e':
# This is how you would refer to the fields
if task['completed'] == 'No':
edit = input('''What would you like to edit:
u - username
d - due date\n''')
if edit == "u":
# updating a field
task['assigned_to'] = input("Please input new user: ")
# Actual file update part
fetched_rows = [task['db_row'] for task in tasks]
with open('tasks.txt') as f, open('temp.txt', 'w') as t:
for db_row, line in enumerate(f):
if db_row in fetched_rows:
fetched_rows.remove(db_row)
print(', '.join(v for k, v in list(tasks.pop(0).items())[2:]), file=t)
else:
print(line.strip(), file=t)
os.remove('tasks.txt')
os.rename('temp.txt', 'tasks.txt')
添加回答
举报