从txt文件中读取信息并将其存储在字典中



我需要从文本文件中获取信息并将其存储到字典

只有一行信息被存储在字典中,我如何让所有的行都被存储?

text = '''
admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will be using this program., 10 Oct 2019, 20 Oct 2019, No
admin, Assign initial tasks, Use taskManager.py to assign each team member with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No
'''

tasks = {}
with open('tasks.txt', 'r', encoding='utf-8') as file:

for line in file:
temp = line.split(", ")
user = temp[0]
title = temp[1]
description = temp[2]
due_date = temp[3]
date_assigned = temp[4]
status = temp[5]

tasks[user] = {'title': title, 'description': description, 'due date': due_date, 'date assigned': date_assigned, 'status': status}
print(tasks)

您的结果字典中有相同的键admin,第一个键被第二个键替换,因此修改您的文本文件以给出不同的名称。如果一个用户有多个分配,可以使用以下代码:

text = '''
admin, Register Users with taskManager.py, Use taskManager.py to 
add the usernames and passwords for all team members that will be 
using this program., 10 Oct 2019, 20 Oct 2019, No
admin, Assign initial tasks, Use taskManager.py to assign each team 
member with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No
'''

tasks = {}
with open('tasks.txt', 'r', encoding='utf-8') as file:
for line in file:
temp = line.split(", ")
user = temp[0]
title = temp[1]
description = temp[2]
due_date = temp[3]
date_assigned = temp[4]
status = temp[5]
if user in list(tasks):
tasks[user].append({'title': title, 'description': description,
'due date': due_date, 'date assigned': date_assigned, 'status': status})
else:
tasks[user] = [{'title': title, 'description': description,
'due date': due_date, 'date assigned': date_assigned, 'status': status}]
print(tasks)

这应该打印:

{'admin': [{'title': 'Register Users with taskManager.py', 'description': 'Use taskManager.py to add the usernames and passwords for all team members that will be using this program.', 'due date': '10 Oct 2019', 'date assigned': '20 Oct 2019', 'status': 'Non'}, {'title': 'Assign initial tasks', 'description': 'Use taskManager.py to assign each team member with appropriate tasks', 'due date': '10 Oct 2019', 'date assigned': '25 Oct 2019', 'status': 'Non'}]}

相关内容

  • 没有找到相关文章

最新更新