Adding a error message in Python as well as commands - python

#!/usr/bin/env python3
import csv
# a file in the current directory
FILENAME = "contacts.csv"
def write_contacts(contacts):
with open(FILENAME, "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(contacts)
def read_contacts():
contacts = []
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
for row in reader:
contacts.append(row)
return contacts
def list_contacts(contacts):
for i in range (len(contacts)):
contact= contacts[i]
print(str(i+1) +"."+ contact[0])
print()
def view_contact(contacts):
pos = int(input("Number: "))
if not (pos-1)in range(len(contacts)):
print(str(pos) + ' not in list, try again')
view(contacts)
return
contact = []
print(name + email + phone+".\n")
print()
def delete_contact(contacts):
index = int(input("Number: "))
contact = contacts.pop(index -1)
write_contacts(contacts)
print(contact[0]+" was deleted.\n")
def add_contact(contacts):
name=input("Name: ")
email=input("Email: ")
phone=input("Phone number: ")
contact= []
contact.append(name)
contact.append(email)
contacts.append(contact)
write_contacts(contacts)
print(name + " was added.\n")
def display_menu():
print("Contact Manager")
print()
print("COMMAND MENU")
print("list - List all contacts")
print("view - View a contact")
print("add - Add a contact")
print("delete- Delete a contact")
print()
print()
def main():
display_menu()
contacts = read_contacts()
while True:
command = input("Command: ")
if command.lower() == "list":
list_contacts(contacts)
elif command.lower()== "view":
view_contact(contacts)
elif command.lower()== "add":
add_contact(contacts)
elif command.lower()== "delete":
delete_contact(contacts)
break
else:
print("Not a valid command. Please try again.\n")
print("Bye!")
if __name__ == "__main__":
main()
This all my code. I'm trying to figure out how to make the delete and view commands display an error message when the user enters a number that is invalid but it's not working. I'm also trying to view a contact when the user selects a specific number form list which would then display the email name and phone number of that selected number. I'm currently stuck
The errors im getting are
raceback (most recent call last):
, line 93, in
main()
, line 81, in main
view_contact(contacts)
, line 32, in view_contact
view(contacts)
NameError: name 'view' is not defined

I don't think you has a good start with list into cvs using append, anyway is your example.
You can use remove to remove your contact from list, see examples with list: http://www.thegeekstuff.com/2013/06/python-list
when the user select a specific number from list , just read by stepping to the number phone because you add with: name + email + phone.
adding an error message , use: try except finally

Related

Saving to CSV file when using Class attribute

Ok so I am trying really hard to get this working. I think I am still not so familiar with the self argument yet, not sure if that matters in this case but I want to append user input once I choose number 1 in the menu and input data that appends to user_list and eventually saves in csv file. But I only get the code <main.User object at 0x7f36d7ccdfa0> in the csv file once I put in the data throught the program
import csv
user_list = []
class User:
def __init__(self, first, last):
self.first = first
self.last = last
self.email = first + '.' + last + '#expressdelivery.com'
def menu():
while True:
print("[1]. Add/remove/update: user to the system.")
try:
option = int(input("Choose from the menu: "))
if option == 1:
user_list.append(User(first = input("Name: "), last = input("Last: ")))
with open('User.csv', 'w') as file:
writer = csv.writer(file)
writer.writerow(user_list)
return(menu())
else:
print("Program quits")
break
except:
print("Error")
menu()

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.

Displaying Specific Information from a List in using User Input - Python 3

Before I state my question I would like to start by saying that I am a beginner at Python programming. I am about half way through my first ever programming class. With that being said I have also researched and used the search engines to look for information on the topic I am working on but I have not found anything that has been either helpful or specific enough to my problem. I have looked through Stack Overflow including browsing the similar questions dialogue. My hope is that this will not be down voted or marked as a duplicate before I get any helpful information.
I am creating a contacts manager program that uses a list of contact names, email addresses, and phone numbers stored in a CSV file. My program should allow the user to display a list of all the contact names, add/delete contacts, and view specific contact information. I am having trouble with the final requirement. Everything else in the program is working and displaying in the console like it should. The code for the entire program is found below;
#!/user/bin/env python3
# Contacts Manager Program
#Shows title of program at start.
print("The Contact Manager Program")
print()
#Imports CSV Module
import csv
#Defines global constant for the file.
FILENAME = "contacts.csv"
#Displays menu options for user, called from main function.
def display_menu():
print("COMMAND MENU")
print("list - Display all contacts")
print("view - View a contact")
print("add - Add a contact")
print("del - Delete a contact")
print("exit - Exit program")
print()
#Defines write funtion for CSV file.
def write_contacts(contacts):
with open(FILENAME, "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(contacts)
#Defines read function for CSV file.
def read_contacts():
contacts = []
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
for row in reader:
contacts.append(row)
return contacts
#Lists the contacts in the list with the user inputs the "list" command.
def list_contacts(contacts):
for i in range(len(contacts)):
contact = contacts[i]
print(str(i+1) + ". " + contact[0])
print()
#List a specific contacts information when the user inputs the "view" command.
def view_contact(number):
#Adds contact to the end of the list when user inputs the "add" command.
def add_contact(contacts):
name = input("Name: ")
email = input("Email: ")
phone = input("Phone: ")
contact = []
contact.append(name)
contact.append(email)
contact.append(phone)
contacts.append(contact)
write_contacts(contacts)
print(name + " was added.\n")
#Removes an item from the list.
def delete_contact(contacts):
number = int(input("Number: "))
if number < 1 or number > len(contacts): #Display an error message if the user enters an invalid number.
print("Invalid contact number.\n")
else:
contact = contacts.pop(number-1)
write_contacts(contacts)
print(contact[0] + " was deleted.\n")
#Main function - list, view, add, and delete funtions run from here.
def main():
display_menu()
contacts = read_contacts()
while True:
command = input("Command: ")
if command.lower() == "list":
list_contacts(contacts)
elif command.lower() == "view": #Store the rest of the code that gets input and displays output in the main function.
view_contact(contacts)
elif command.lower() =="add":
add_contact(contacts)
elif command.lower() == "del":
delete_contact(contacts)
elif command.lower() == "exit":
break
else:
print("Not a valid command. Please try again.\n")
print("Bye!")
if __name__ == "__main__":
main()
I need the view_contact function to get a number as input from the user and then print the corresponding contact information that is related the the line number in the CSV file.
It looks like you storing contacts in form of lists in your .csv file. Use read_contacts to read all the contacts from that csv file, then get contact specified by number parameter. That's it.
def view_contact(number):
contacts = read_contacts()
specified_contact = contacts[number]
print("Name: ", specified_contact[0])
print("Email: ", specified_contact[1])
print("Phone: ", specified_contact[2])

python sava data into txt file

I have problem to create a full coding python file handling. I need all data functions in python will be save in txt file. Below is my coding.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = int(input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top
Management (e.g 1/2/3/4): "))
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
serLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%li "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
Actually, this program should have five requirements. First is staffRegistration(), staffLogin(), staffAttendance(), staffLeaveApplication(), approval() but I have done for two requirements only and I get stuck at staffLogin(). I need every function will be save in txt file (I mean the data in function).
In line 32 you try to convert a String into Integer. Besides, in your main function, you have an unresolved variable userLogin.
The other problem is in line 43 (staffLogin function), You want to write a long integer but you pass a string. I have tried to fix your code except for userLogin in main.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top Management (e.g 1/2/3/4): ")
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
userLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%s "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
There are a lot of problems in the staffLogin() function. e.g. the result of the first input()is bound to serLogin, but this should be userLogin.
If that is corrected, a password is read from the user, but nothing is ever done with it. Should the password be treated as an integer?
Also, if the user enters 2 at first prompt, the code will not set username but it will still try to write username to the file. That will raise a NameError exception.
Finally, the code attempts to write the characters in userLogin to the file as though they are integers. Not only will that not work, it doesn't make sense. Perhaps this should be writing the password to the file?

Rewriting CSV file in Python messes up index of rows

This is my entire project at the moment. The original CSV file has 4 rows with a contacts name, email, and phone information. The "list" "view" and "add" functions work fine until I use the "delete" function. In order to delete the desired line, I put the file in a list, deleted the row the user inputs, and rewrote the list into the CSV file with what appears to be good format.
import csv
print("Contact List\n")
print(" list - Display all contacts\n","view - View a contact\n","add - Add a contact\n", "del - Delete a contact\n", "exit - Exit program\n")
def main():
userCom = input("\nCommand: ")
if userCom == "list":
lists()
elif userCom == "view":
count()
elif userCom == "add":
add()
elif userCom == "del":
delete()
elif userCom == "exit":
exitt()
else :
print("Invaild input, try again")
main()
def count():
counter = 1
with open("contacts.csv") as file:
number = file.readline()
for line in file:
counter = counter +1
view(counter)
def lists():
with open("contacts.csv", newline="") as file:
reader = csv.reader(file)
counter = 0
for row in reader:
print(int(counter) + 1, ". ",row[0])
counter = counter+1
main()
def view(count):
num = input("Enter a contact's number to view their information: ")
while num.isdigit() == False or int(num) < 1 or int(num) > int(count):
print("Invaild input, try again")
view(count)
reader = csv.reader(open("contacts.csv"))
lines = list(reader)
print("Name: ",lines[int(num)-1][0],"\nEmail: ",lines[int(num)-1][1],"\nPhone Number: ",lines[int(num)-1][2])
main()
def add() :
name = input("Name: ")
email = input("Email: ")
phone = input("Phone: ")
added = [name,",",email,",",phone]
with open("contacts.csv", "a") as file:
for item in added:
file.write(item)
print(name, " was added.")
file.close()
main()
def delete():
deleted = input("Enter number to delete: ")
reader = csv.reader(open("contacts.csv"))
contacts = list(reader)
del contacts[int(deleted)-1]
with open("contacts.csv", "w") as file:
writer = csv.writer(file)
writer.writerows(contacts)
print("Number ",deleted," was deleted.")`enter code here`
file.close()
main()
main()
When I use delete and try the "list" or "view" features, I get this error message:
Traceback (most recent call last):
File "C:\Users\Test\Desktop\contacts_1.py", line 81, in <module>
main()
File "C:\Users\Test\Desktop\contacts_1.py", line 15, in main
delete()
File "C:\Users\Test\Desktop\contacts_1.py", line 72, in delete
main()
File "C:\Users\Test\Desktop\contacts_1.py", line 9, in main
lists()
File "C:\Users\Test\Desktop\contacts_1.py", line 35, in lists
print(int(counter) + 1, ". ",row[0])
IndexError: list index out of range
Any help helps!
This is because your row doesnt contain any line, so it doesn't even have the 0 index.
Yo must check if the list contain something before accessing any item inside:
if row:
print(row[0])
As I said in comment, your solution is flawed, because it will overflow the stack at some point. You should use an infinite loop instead of calling the main function again and again
def main():
while 1:
userCom = input("\nCommand: ")
if userCom == "list":
lists()
elif userCom == "view":
count()
elif userCom == "add":
add()
elif userCom == "del":
delete()
elif userCom == "exit":
exitt()
else:
print("Invaild input, try again")
# main()

Categories

Resources