python - 如何在 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()
解决方案
做这样的事情,每个名称行都进入 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
推荐阅读
- r - 在 R 中合并数据集
- python-3.x - Python3 f 字符串与 .replace
- amazon-web-services - 有没有办法从现有的 aws 环境生成 serverless.yml?
- google-apps-script - 将一个 google sheet 文档修改到另一个 sheet 文档的时间添加
- kotlin - 更改 Kotlin JVM 目标会导致任何问题吗?
- node.js - 将 mysql 连接作为参数传递给表达式路由中间件函数
- amazon-s3 - 尝试在无服务器框架中为 AWS Lambda 函数创建多个 s3 存储桶时,Yaml 文件出错
- flutter - 如何在容器内显示 ListView 而无需在 Flutter 中设置容器高度?
- c++ - 处理 TCP 数据时会发生什么
- javascript - 如何使用从函数返回的数值进行进一步计算