我打算通过字典将用户输入的联系人列表以及姓名和电话号码保存在.csv文件中。
问题在于,只有名称保存在.csv文件中,而数字被省略了。
contacts={}
def phone_book():
running=True
while running:
command=input('A(dd D)elete L)ook up Q)uit: ')
if command=='A' or command=='a':
name=input('Enter new name: ')
print('Enter new number for', name, end=':' )
number=input()
contacts[name]=number
elif command=='D' or command=='d':
name= input('Enter the name to delete: ')
del contacts[name]
elif command=='L' or command=='l':
name= input('Enter name to search: ')
if name in contacts:
print(name, contacts[name])
else:
print("The name is not in the phone book, use A or a to save")
elif command=='Q' or command=='q':
running= False
elif command =='list':
for k,v in contacts.items():
print(k,v)
else:
print(command, 'is not a valid command')
def contact_saver():
import csv
global name
csv_columns=['Name', 'Phone number']
r=[contacts]
with open(r'C:\Users\Rigelsolutions\Documents\numbersaver.csv', 'w') as f:
dict_writer=csv.writer(f)
dict_writer.writerow(csv_columns)
for data in r:
dict_writer.writerow(data)
phone_book()
contact_saver()
答案 0 :(得分:0)
在我阅读您的代码contacts
时,
{
'name1': '1',
'name2': '2'
}
键是名称,值是数字。
但是当您执行r = [contacts]
并遍历r for data in r
时会搞砸,我猜是您的代码,因为您是将字典值传递给writerow
而不是列表[名称,数字]
您可以在这里做两件事。通过以下方式正确解析联系人:
for k, v in contacts.items():
dict_writer.writerow([k, v])
或将联系人适当地构建为带有字典的列表
[{
'name': 'name1',
'number': 1
}]
因此您可以创建DictWriter
fieldnames = ['name', 'number']
writer = csv.DictWriter(f, fieldnames=fieldnames)
...
# then you can insert by
for contact in contacts:
writer.writerow(contact) # which should look like writer.writerow({'name': 'name1', 'number': 1})