【发布时间】:2016-08-29 14:10:18
【问题描述】:
我是所有这些编码方面的新手,但即使事情不起作用,我也有很多动力。
我正在尝试使用 CSV 文件处理字典。我可以打开并编辑一个新文件,但我想我在尝试从 csv 文件中读取时遗漏了一些东西。 我在第 39-41 行遇到错误,我可能做错了什么,但它是什么? 代码如下:
import csv
import os
import os.path
phonebook = {}
def print_menu():
print('1. Print phone book')
print('2. add phone book')
print('3. look for number using first name only')
print('4. look by last name')
print('5. exit')
print()
menu_selection = 0
while menu_selection != 5:
if os.path.isfile('my_phonebook.csv') == True:
csv_file = open('my_phonebook.csv', 'a', newline = '')
writer = csv.writer(csv_file)
else:
csv_file = open('my_phonebook.csv', 'w', newline = '')
writer = csv.writer(csv_file)
headers = ['first_name','last_name','phone_number']
writer.writerow(headers)
print_menu()
menu_selection = int(input('type menu selection number'))
if menu_selection == 2: #add list in phone book
first_name = input("enter first name: ")
last_name = input("enter last name: ")
phone_number = input("enter phone number: ")
writer.writerow([first_name,last_name,phone_number])
csv_file.close()
elif menu_selection == 1: #print phone book
print("phone book:")
listGen = csv.reader(csv_file, delimiter=' ', quotechar='|') #error starts here and in the next two rows...
for row in csv_file:
print(row)
elif menu_selection == 3: #look for number using first name only
print('look up number')
first_name = input('first name:')
if first_name in phonebook:
print('the number is', phonebook[phone_number])
else:
print('name not found')
elif menu_selection == 4: #print all details of last name entered
print('search by last name')
last_name = input('please enter last name: ')
for row in csv_file:
print(row)
【问题讨论】:
-
您可以编辑您的问题并添加您获得的错误吗?在 python 中,这些消息包含大量信息,只要稍加训练,您只需阅读它们即可轻松纠正大部分错误。
-
按照python的文档示例怎么样:docs.python.org/2/library/csv.html#examples?
标签: python csv dictionary