dictionary python with a csv file - python

I'm new at all this coding but have lots of motivation even when things don't work.
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:
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)

Does the file have any contents? Looks like you're trying to loop over an empty iterator of lines. Try something like...
for row in csv_file:
print(row)
else:
print('no phone numbers')
And see what you get.

Please check the below code.
There were some other errors also which I tried to fix.Did couple of changes for the same.
For reading csv, I didn't use csv reader module.
If you want to use that, please replace the code in search() function.
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()
def search(name):
phonebook = open('my_phonebook.csv','r')
name_found = True
for line in phonebook:
if name in line:
fname,lname,num = line.split(',')
print "First Name is ",fname.strip()
print "Last Name is ",lname.strip()
print 'the number is', num.strip()
name_found = True
if not name_found:
print('name not found')
return
menu_selection = 0
while menu_selection != 5:
print_menu()
menu_selection = int(input('type menu selection number - '))
if menu_selection == 2: #add list in phone book
if os.path.isfile('my_phonebook.csv') == True:
csv_file = open('my_phonebook.csv', 'a')
writer = csv.writer(csv_file)
else:
csv_file = open('my_phonebook.csv', 'w')
writer = csv.writer(csv_file)
headers = ['first_name','last_name','phone_number']
writer.writerow(headers)
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:")
if os.path.isfile('my_phonebook.csv') == True:
csv_file=open('my_phonebook.csv','r')
for row in csv_file:
print(row)
csv_file.close()
else:
print "Phone book file not created. First create it to read it"
elif menu_selection == 3: #look for number using first name only
print('look up number')
first_name = input('first name:')
search(first_name)
elif menu_selection == 4: #print all details of last name entered
print('search by last name')
last_name = input('please enter last name: ')
search(last_name)
Output:
C:\Users\dinesh_pundkar\Desktop>python b.py
1. Print phone book
2. add phone book
3. look for number using first name only
4. look by last name
5. exit
()
type menu selection number - 1
phone book:
Phone book file not created. First create it to read it
1. Print phone book
2. add phone book
3. look for number using first name only
4. look by last name
5. exit
()
type menu selection number - 2
enter first name: "Dinesh"
enter last name: "Pundkar"
enter phone number: "12345"
1. Print phone book
2. add phone book
3. look for number using first name only
4. look by last name
5. exit
()
type menu selection number - 1
phone book:
first_name,last_name,phone_number
Dinesh,Pundkar,12345
1. Print phone book
2. add phone book
3. look for number using first name only
4. look by last name
5. exit
()
type menu selection number - 3
look up number
first name:"Dinesh"
First Name is Dinesh
Last Name is Pundkar
the number is 12345
1. Print phone book
2. add phone book
3. look for number using first name only
4. look by last name
5. exit
()
type menu selection number - 4
search by last name
please enter last name: "Pundkar"
First Name is Dinesh
Last Name is Pundkar
the number is 12345
1. Print phone book
2. add phone book
3. look for number using first name only
4. look by last name
5. exit
()
type menu selection number - 5
C:\Users\dinesh_pundkar\Desktop>

Related

Repository by using python

I have made a repository or a contact book using python:
But i am only able to use search function on one name at a time so i want to write code in such a way that i can search multiple name and related contact info at the same time.
num=int(input("Total no. of repository user wants to create: "))
names=[]
contact_numbers=[]
for i in range(num):
name = input("Enter the Name: ")
contact_number = input("Enter the Phone Number: ")
names.append(name)
contact_numbers.append(contact_number)
print("\n\tName\t\t\tPhone Number\n")
#Creating a list of names & contact in tabular form:
for i in range(num):
print("\t{}\t\t\t{}".format(names[i], contact_numbers[i]))
#Search:
while True:
choice=int(input("\n\nPress 1 or 2\n1=To search\n2=To Exit\n"))
if choice == 1:
search_name=input("\n Enter the name you want to search: ")
print("\nSEARCH RESULT :")
if search_name in names:
index = names.index(search_name)
contact_number = contact_numbers[index]
print("Name: {}, Phone Number: {}".format(search_name, contact_number))
else:
print("Name not found in repository")
else:
print("Exit")
break
You can simplify this greatly by using the most appropriate structures. In this case a dictionary is ideal.
contacts = {}
while (name := input('Enter name or <return> when finished: ')):
phone_number = input('Enter phone number: ')
contacts[name] = phone_number
while (names := input('Enter name or comma-separated list of names to search or <return> when finished: ')):
for name in names.split(','):
print(f'{name} {contacts.get(name, "Not found")}')

Delete a line (name, contactnumber, emailaddress) by just searching for name in a phonebook

Good evening, I have a phonebook code but I am missing the delete feature. I cannot seem to make the delete feature work. All other features like insert, view, add contacts are working already.
I created a phnoebook txt file to store any entries.
phonebook = "d://phonebook.txt"
pbfile = open(phonebook, "a+")
pbfile.close
def show_main_menu():
''' Show main menu for Phone List '''
print("\n *** Phone List Menu ***\n"+
"------------------------------------------\n"+
"Enter 1, 2, 3 or 4:\n"+
"1: Display Your Contacts Records\n" +
"2: Add a New Contact Record\n"+
"3: Search your contacts\n"+
"4: Delete a Contact Record\n"+
"5: Quit\n**********************")
choice = input("Enter your choice: ")
if choice == "1":
pbfile = open(phonebook, "r+")
file_contents = pbfile.read()
if len(file_contents) == 0:
print("Phone List is empty")
else:
print (file_contents)
pbfile.close
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "2":
enter_contact_record()
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "3":
search_contact_record()
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "4":
delete_contact_record()
user_entry = ("Please Enter to Return to Main Menu ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone List")
else:
print("Wrong choice, Please Enter [1 to 5]\n")
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
I added the main menu above to show the menu of the phone book, there should be another choice to delete a contact.
The following code is to search for contact. It will show if a contact is already in the phone book but will mention not on record if there is no contact by the name they searched.
def search_contact_record():
''' This function is used to searches a specific contact record '''
contact_search = input("Enter First name to search for contact record: ")
contact_search = contact_search.title()
pbfile = open(phonebook, "r+")
file_contents = pbfile.readlines()
found = False
for line in file_contents:
if contact_search in line:
print("You searched for:", end=" ")
print (line)
found=True
break
if found == False:
print("There's no contact Record in Phone List with name = " + contact_search )
The next function is to enter contact and add it to the phonebook txt file created in the beginning.
def enter_contact_record():
''' It collects contact info firstname, last name, email and phone '''
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
email = input('Enter E-mail: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + email + "]\n")
pbfile = open(phonebook, "a")
pbfile.write(contact)
print( "This contact\n " + contact + "has been added successfully!")
#def delete_contact():
show_main_menu()
I got confused on the part how to delete the contact from the txt phonebook. Last delete lines I have trying was the following
def delete_contact_record():
#Initiate a name variable
contact_delete = input('Enter the name of the contact you wish to delete: ').title()
pbfile = open(phonebook, "r+")
file_contents = pbfile.readlines()
found = False
for line in file_contents:
if contact_delete in line:
confirm = input('Are you sure you wish to delete '+contact_delete+' y/n?: ')
print(confirm)
if confirm == 'y':
del phonebook[contact_delete]
found = True
if found == False:
print('That contact does not exist! Return to the main menu to enter the contact')
it works up to the line asking for confirmation y/n. But when I enter Y, I get a TypeError: 'str' object does not support item deletion
Thank you.
Your main problem is that your phone book is a flat file. As such, a deletion is "rewrite the entire file, but without the deleted record."
This is, needless to say, very inefficient.
You will also have problems in the future with spurious matches for searches, since contact_search in line is perfectly happy to match parts of names.
Personally, I'd recommend using an SQLite3 database instead of a flat file (SQLite3 support is built in to Python). SQLite3 databases are actually single files, but you can use almost all of the SQL language to perform structured queries, and let it manage the file for you.
If writing SQL is too daunting, the SQLAlchemy Python package can help by making database tables work like Python classes.

Adding user input to csv file

Problem:
Looking for assistance in adding user input such as Last Name, First Name, Credit Card number, etc etc to a csv file in Python. I assume I would have to add similar code for each of the user inputs (lastName, firstName, arrivalDate, departureDate, enterRate, enterCC, enterEXP)
Context:
This program mimics a hotel property management system, where guests information such as room number, arrival, departure, CC# are stored. In addition, the program allows the user to input new guests with the 'Make Reservation' menu selection.
Relevant code is attached - thank you!
elif menuSelect == "6":
lastName = input("Please Enter a Last Name: ")
firstName = input("Please Enter a First Name: ")
arrivalDate = input("Please Enter an Arrival Date: ")
departureDate = input("Please Enter a Departure Date: ")
enterRate = input("Please enter Rate Amt: $")
enterCC = input("Please enter a valid Credit Card: ")
enterEXP = input("What is the Expiration Date? mm/yy: ")
You could use the python built-in csv library:
To use it simply write:
import csv
with open('filename.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
and to write a row:
csvwriter.writerow(['Column1', 'Column2', 'Column3'])
Note: If you want to add input to an existing file replace the 'w' in open with 'a'

How to make data entered by user to appear below headers

This is my code for entering student details. Once the user has entered the details and inputs yes, the details are exported to StudentDetails.csv (Microsoft Excel) where it should go below the headers but ends up going somewhere else.
def EnterStudent():
uchoice_loop = False
ask_loop = False
while uchoice_loop == False:
surname = raw_input("What is the surname?")
forename = raw_input("What is the forname?")
date = raw_input("What is the date of birth? {Put it in the format D/M/Y}")
home_address = raw_input("What is the home address?")
home_phone = raw_input("What is the home phone?")
gender = raw_input("What is their gender?")
tutor_group = raw_input("What is their tutor group?")
email = (forename.lower() + surname.lower() + ("#school.com"))
print(surname+" "+forename+" "+date+" "+home_address+" "+home_phone+" "+gender+" "+tutor_group+" "+email)
ask = raw_input("Are these details correct?"+"\n"+"Press b to go back, or yes to add entered data on your student.").lower()
if ask == "yes":
f = open("StudentDetails.csv","rt")
lines = f.readlines()
f.close()
lines.append(surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email+"\n")
f = open("StudentDetails.csv", "w")
f.writelines(lines)
f.close()
uchoice_loop = True
printMenu()
elif ask == "b":
uchoice_loop = False
else:
print("Plesase enter 'b' to go back or 'yes' to continue")
This is my csv file.
enter image description here
There's a few things you can do to make this work. You dont need to open the StudentDetails.csv and read all of the lines. Instead you can make a lines string variable and append it the the StudentDetails.csv like in the example below
#f = open("StudentDetails.csv","rt")
#lines = f.readlines()
#f.close()
lines = surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email
# the "a" appends the lines variable to the csv file instead of writing over it like the "w" does
f = open("StudentDetails.csv", "a")
f.writelines(lines)
f.close()
uchoice_loop = True
Eric is right in that you best open the file in append-mode (see https://docs.python.org/3.6/library/functions.html#open) instead of cumbersomely reading and rewriting your file over and over again.
I want to add to this that you probably will enjoy using the standard library's csv module as well (see https://docs.python.org/3.6/library/csv.html), especially if you want to use your output file in Excel afterwards.
Then, I'd also advise you to not use variables for while loop conditionals, but learning about the continue and break statements. If you want to break out of the outer loop in the example, research try, except and raise.
Finally, unless you really have to use Python 2.x, I recommend you to start using Python 3. The code below is written in Python 3 and will not work in Python 2.
#!/usr/bin/env python
# -*- codig: utf-8 -*-
import csv
def enterStudent():
b_or_yes = 'Press b to go back, or yes to save the entered data: '
while True:
surname = input('What is the surname? ')
forename = input('What is the first name? ')
date = input(
'What is the date of birth? {Put it in the format D/M/Y} ')
home_address = input('What is the home address? ')
home_phone = input('What is the home phone? ')
gender = input('What is the gender? ')
tutor_group = input('What is the tutor group? ')
email = forename.lower() + surname.lower() + '#school.com'
studentdata = (
surname,
forename,
date,
home_address,
home_phone,
gender,
tutor_group,
email)
print(studentdata)
while True:
reply = input('Are these details correct?\n' + b_or_yes).lower()
if reply == 'yes':
with open('studentdetails.csv', 'a', newline='') as csvfile:
studentwriter = csv.writer(csvfile, dialect='excel')
studentwriter.writerow(studentdata)
break
elif reply == 'b':
break
if __name__ == '__main__':
enterStudent()
Best of luck!

I am trying to create an address book program that will append user input to its appropriate list

I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()

Categories

Resources