首页 > 解决方案 > 如何在 Python 中将文件打开到字典

问题描述

我有一个包含一堆姓名和电子邮件的文件。它们的写法如下:

姓名
电子邮件
姓名
电子邮件

我不知道如何打开文件并逐行读取它在我的字典中将“名称与电子邮件”配对的位置

当我在字典中手动输入名称/电子邮件时,我得到了代码,但我需要从文件中提取它。

LOOK_UP=1
ADD= 2
CHANGE= 3
DELETE=4
QUIT=5

def main():
    emails={}
    with open('phonebook.in') as f:
        for line in f:
            (name, email)=line.split
            emails[name]=email
        
        
    
    choice=0
    while choice !=QUIT:
        choice= get_menu_choice()
        if choice == LOOK_UP:
            look_up(emails)
        elif choice == ADD:
            add(emails)
        elif choice == CHANGE:
            change(emails)
        elif choice == DELETE:
            delete(emails)
    
def get_menu_choice():
    print('Enter 1 to look up an email address')
    print('Enter 2 to add an email address')
    print('Enter 3 to change an email address')
    print('Enter 4 to delete an email address')
    print('Enter 5 to Quit the program')
    print()
    choice= int(input('Enter your choice: '))

    while choice <LOOK_UP or choice >QUIT:
        choice= int(input('Enter a valid choice'))
    return choice
def look_up(emails):
    name= str(input('Enter a name: '))
    value=(emails.get(name, 'Not found.'))
    print(value)
    print()
    
def add(emails):
    name= str(input('Enter a name: '))
    emailsaddy= input(' Enter a email address: ')

    if name not in emails:
        emails[name]= emailsaddy
        print()
    else:
        print('That contact already exists')
        print()
def change(emails):
    name=str(input ('Enter a name: '))
    if name in emails:
        emailsaddy= str(input(' Enter a new email: '))
        emails[name]= emailsaddy
    else:
        print('That contact does not exist')
def delete(emails):
    name=str(input ('Enter a name: '))

    if name in emails:
        del emails[name]
    else:
        print('That contact is not found')
main()
    

标签: python

解决方案


做这样的事情,每个名称行都进入 if 语句,每个电子邮件行都进入 else 并添加到目录。

emails = {}
i = 0
with open('phonebook.in') as f:
    for line in f:
        if i == 0:
            name = line
            i = 1
        else:
            email = line
            emails[name] = email
            i = 0

推荐阅读