dictionary python with a csv file
<p>I'm new at all this coding but have lots of motivation even when things don't work.</p>

<p>I'm trying to work on a dictionary with a CSV file. I get to open and edit a new file but I think I'm missing something when trying to read from the csv file.
I'm getting errors in rows 39-41 i'm probably doing something wrong but what is it?
Here is the code:</p>

<pre><code>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)
</code></pre>

<p>Does the file have any contents? Looks like you're trying to loop over an empty iterator of lines. Try something like...</p>

<pre><code>for row in csv_file:
    print(row)
else:
    print('no phone numbers')
</code></pre>

<p>And see what you get.</p>

python csv dictionary