簡體   English   中英

從一個txt文件中讀取信息並存入字典

[英]Reading information from a txt file and storing it in a dictionary

我需要從 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': 'No\n'}, {'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': 'No\n'}]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM