Adding user input to csv file - python

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'

Related

Python: CSV file reading and comparison of cell value Vs input value

I have a CSV file named 'file_name.csv' containing data:
account_holder_name, account_number, account_balance
Ganesh, 12345, 100
Parvati, 23456, 10000
Waheguru, 98765, 12098
Input: Above data I have entered using DictWriter function.
Expected Output: If I manually enter 98765 it can read name and balance for particular row.
Actual Output:
Press 1: To Open New Bank Account or Press 2: To Use Existing Account : 2
Enter account holder number: 12345
Enter correct a/c number
Enter correct a/c number
Enter correct a/c number
I used below code:
class Account():
def __init__(self,choice):
self.choice = choice
self.file_name = 'file_name.csv'
self.header = ('account_holder_name', 'account_number', 'account_balance')
def existing_holder(self):
self.account_number = int(input("Enter account holder number: "))
with open(self.file_name, 'r') as csvfile:
csv_reader = csv.DictReader(csvfile, fieldnames=self.header)
self.header = next(csv_reader)
if self.header != None:
for row in csv_reader:
if row['account_number'] == self.account_number:
print(f"Welcome Mr.{row['account_holder_name']}. Following are the choices. Please select : \nPress 1 deposit money \nPress 2 for withdraw money")
else:
print("Enter correct a/c number")
customer_visit = int(input("Press 1: To Open New Bank Account or Press 2: To Use Existing Account : "))
acct1 = Account(customer_visit)
if customer_visit ==2:
acct1.existing_holder()

Listing names still the correct one is quess

I have no idea what I am doing wrong. Here is the question:
● Write a Python program called “John.py” that takes in a user’s input as a String.
● While the String is not “John”, add every String entered to a list until “John” is entered.
Then print out the list. This program basically stores all incorrectly entered Strings in a
list where “John” is the only correct String.
● Example program run (what should show up in the Python Console when you run it):
Enter your name :
Enter your name:
Enter your name:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This is what I have so far:
name_list = [" "]
valid_name = "John"
name = str(input("please enter a name: "))
if name != valid_name.upper():
#name = str(input("please enter a name: ")
name_list.append(name)
name_list += name
elif name == valid_name.upper():
name_list.append(name)
name_list += name
print("Incorrect names that you have added: ")`enter code here`
print(name_list[0:])
You almost got it! just need to use a while loop instead of a if/else:
name_list = []
valid_name = "John"
name = str(input("please enter a name: "))
while name != valid_name:
name_list.append(name)
name = str(input("Incorrect! please enter a name: "))
print(f"Correct! Incorrect names that you have added: {name_list}")

Python pickles not storing data

I am trying to create a registrar system through Python with pickles. I have gotten the system to record user input, but it does not save it for future implementations of the program.
Here is the code that will start the program:
import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *
prompt = "Please select an option: \n 1 Create a new course \n 2 Schedule a new course offering \n 3 List this school's course catalogue \n 4 List this school's course schedule \n 5 Hire an instructor \n 6 Assign an instructor to a course \n 7 Enroll a student \n 8 Register a student for a course \n 9 List this school's enrolled students \n 10 List the students that are registered for a course \n 11 Submit a student's grade \n 12 Get student records \n 13 Exit"
farewell = "Thank you for using the Universal University Registrar System. Goodbye!"
print ("Welcome to the Universal University Registration System.")
print ("\n")
try: #As long as CTRL-C has not been pressed, or 13 not been input by user.
input_invalid = True
while input_invalid:
inst = input("Please enter the name of your institution. ").strip()
domain = input("Please enter the domain. ").strip().lower()
if inst == "" or domain == "":
print("Your entry is invalid. Try again.")
else:
input_invalid = False
schoolie = Institution(inst, domain)
if Path(inst + '.pkl').exists() == False:
with open(inst + '.pkl', 'r+b') as iptschool:
schoolie = pck.load(iptschool)
while True:
print (prompt)
user_input = input("Please enter your choice: ")
try:
user_input = int(user_input)
if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
except ValueError:
print("Not a valid number. Please try again.")
if user_input == 1: #Create a new course
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_name = input("Please enter a course name: ").strip()
input_department = input("Please enter the course's department: ").strip()
input_number = input("Please enter the course's number (just the number, not the departmental prefix): ").strip()
try:
input_number = int(input_number)
except ValueError:
print ("Please print an integer. Try again.")
input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer: ").strip()
try:
input_credits = int(input_credits)
except ValueError:
print ("Please print an integer. Try again.")
if input_name != "" and input_department != "" and input_number and input_credits:
input_invalid2 = False #Valid input
else:
print("One or more of your entries is invalid. Try again.")
added_course = Course(input_name, input_department, input_number, input_credits)
for course in schoolie.course_catalog:
if course.department == input_department and course.number == input_number and course.name == input_name:
print("That course is already in the system. Try again.")
input_invalid2 == True
if input_invalid2 == False:
schoolie.add_course(added_course)
print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))
And here is the second option, which SHOULD reveal that it is stored, but it does not.
elif user_input == 2: #Schedule a course offering
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_department = input("Please input the course's department: ").strip()
input_number = input("Please input the course's number: ").strip()
course = None
courseFound = False
for c in schoolie.course_catalog:
if c.department == input_department and c.number == input_number: #Course found in records
courseFound = True
course = c
input_section_number = input("Please enter a section number for this course offering: ").strip()
input_instructor = input("If you would like, please enter an instructor for this course offering: ").strip()
input_year = input("Please enter a year for this course offering: ").strip()
input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER: ").strip().upper()
if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
if input_instructor != "": #Instructor to be added later, if user chooses option 6.
added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
else:
added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
schoolie.add_course_offering(added_course_offering)
input_invalid2 = False #Valid input
print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
else:
print("One or more of your entries is invalid. Try again.")
if courseFound == False: #If course has not been found at the end of the loop:
print("The course is not in our system. Please create it before you add an offering.")
break
By the way, I think I have the system closing properly. Correct me if I'm wrong:
elif user_input == 13: #Exit
with open(inst + '.pkl', 'wb') as output:
pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
del schoolie
print (farewell)
sys.exit()
except KeyboardInterrupt: #user pushes Ctrl-C to end the program
print(farewell)
I believe that there is something wrong with the way that I am setting up the pickles files. I'm creating them, but I seem not to be putting data into them.
I apologize for the long-winded nature of this question, but I hope that the details will help you understand the problems that I've been having. Thanks in advance for the help!
it seems you may have dump and load reversed: (from the docs)
Signature: pck.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')
Docstring:
Read and return an object from the pickle data stored in a file.
Signature: pck.dump(obj, file, protocol=None, *, fix_imports=True)
Docstring:
Write a pickled representation of obj to the open file object file.
With all those lines of code, it does get a little confusing, but I don't see any code that is pickling and writing the objects to a file.
Before anything else, you should assign the file to a variable so you can reference it. To do this, you'll have code similar to this:MyFile = open("FileName.extension","wb"). MyFile can be any name you want, it will be what you use later to reference the file. FileName is the name of the file itself. This is the name it will have in File Explorer. .extension is the file's extension, specifying the type of file. You should use .dat for this. wb is the file access mode. "w" means write, and "b" means binary. (Pickled objects can only be stored in a binary file.)
To write the pickled objects, you'll need this code:pck.dump(object,MyFile). (Usually, you would use pickle.dump(object,MyFile), but you imported pickle as pck.)
After writing the data to the file, you'll want to retrieve it. To do this, the "wb" instance of MyFile needs to be closed like this:MyFile.close(). Then you'll need to re-open the file in read mode using the following code:MyFile = open("FileName.extension","rb") Then you would use this:object = pickle.load(MyFile) to read the data. In the preceding example, (the load function), your object must have the same name as when you pickled it using the dump function. (pck.dump(object,MyFile))
In the end, you'll end up with something similar to this:
if writing conditions are true:
MyFile = open("FileName.dat","wb")
pickle.dump(object,MyFile) # This will be repeated for each object.
MyFile.close()
if reading conditions are true:
MyFile = open("FileName.dat","rb")
object = pickle.load(MyFile) # This will be repeated for each object.
MyFile.close()
I'm sorry if this wasn't the answer you wanted. Because of all those lines of code, it is somewhat hard to understand. I need clarification to give a better answer.

dictionary python with a csv file

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>

How to add a another value to a key in python

First I'm sorry this might be a dumb question but I'm trying to self learn python and I can't find the answer to my question.
I want to make a phonebook and I need to add an email to an already existing name. That name has already a phone number attached. I have this first code:
phonebook = {}
phonebook ['ana'] = '12345'
phonebook ['maria']= '23456' , 'maria#gmail.com'
def add_contact():
name = raw_input ("Please enter a name:")
number = raw_input ("Please enter a number:")
phonebook[name] = number
Then I wanted to add an email to the name "ana" for example: ana: 12345, ana#gmail.com. I created this code but instead of addend a new value (the email), it just changes the old one, removing the number:
def add_email():
name = raw_input("Please enter a name:")
email = raw_input("Please enter an email:")
phonebook[name] = email
I tried .append() too but it didn't work. Can you help me? And I'm sorry if the code is bad, I'm just trying to learn and I'm a bit noob yet :)
append isn't working because the dictionary's values are not lists. If you make them lists here by placing them in [...]:
phonebook = {}
phonebook ['ana'] = ['12345']
phonebook ['maria'] = ['23456' , 'maria#gmail.com']
append will now work:
def add_contact():
name = raw_input("Please enter a name:")
number = raw_input("Please enter a number:")
phonebook[name].append(number)

Categories

Resources