Append CSV cell based user input - python

Require help: I have a CSV file named 'file_name.csv' containing data as mentioned below. I am building a small bank project (for self-learning) in which I have used :
function open_account - computer asks name and generate random 3 digit account_number and stores it in CSV file
function existing_holder - computer asks account_number and display name which is already stored using open_account function And give the option to deposit or withdraw money
function deposit - computer asks amount to be deposited. And I want it should get appended in particular account_number which he has entered in existing_holder function and display balance.
Output expected: User enter account_number in existing_holder function and the computer asks amount to be deposited and it adds in particular account_number, account_balance
Please correct me what to use in deposit(). I tried using DicWriter, reader, converting them it list but didn't get code working.
Error: TypeError: 'DictWriter' object is not iterable
account_holder_name, account_number, account_balance
Ganesh, 12345, 100
Parvati, 23456, 10000
Waheguru, 98765, 12098
I used below code:
import random as r
import csv
class Account():
print("Welcome to AV Bank")
def __init__(self,choice):
self.choice = choice
self.account_number = 0
self.file_name = 'file_name.csv'
self.header = ('account_holder_name', 'account_number', 'account_balance')
def open_account(self):
self.new_account_holder_name = str(input("Enter new account holder name: "))
self.account_number = r.randrange(999)
self.new_account_deposit = int(input("To open new a/c, deposit minimum Rs.1000/-: "))
if self.new_account_deposit>=1000:
with open(self.file_name, 'a+', newline='') as csvfile:
write_to_file = csv.DictWriter(csvfile, fieldnames=self.header)
# write_to_file.writeheader()
write_to_file.writerow(
{'account_holder_name': self.new_account_holder_name, 'account_number': self.account_number,
'account_balance': self.new_account_deposit})
print(f"Mr.{self.new_account_holder_name} your a/c has been opened and a/c no. is {self.account_number}, With balance Rs. {self.new_account_deposit}/-")
else:
print("Deposit minimum Rs. 1000/-")
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)
for row in csv_reader:
for acn in (row['account_number']):
if int(row['account_number']) == self.account_number:
print(f"Welcome Mr.{row['account_holder_name']}.Please select : \nPress 1 deposit money \nPress 2 for withdraw money")
break
# else:
# print("Enter correct a/c number")
def deposit(self):
self.amount_added = int(input("Enter the amount to be deposited: "))
with open(self.file_name, 'a+') as file:
writeData = csv.DictWriter(file,fieldnames = self.header)
''' WANT TO ITERATE THE CSV FILE TO GET VALUE self.account_number AND UPDATE self.account_balance AFTER DOING ADDITION OPERATION''
# for self.account_number in line:
# if line[self.account_number] == self.account_number:
# print("God")
# with open(self.file_name, 'a+',newline='') as csvfile:
# csv_append = csv.reader(csvfile)
# line = list(csv_append)
#
# print(line)
#self.header = next(csv_append)
# for row in csv_append:
# #self.balance = int(row['account_balance']
# for acn in (row['account_number']):
# if int(row['account_number']) == self.account_number:
# self.balance = int(row['account_balance'])
# self.new_balance = int(row['account_balance']) + self.amount_added
# csv_append.writerow(self.new_balance)
# print(f"Added Rs. {row['account_balance']} in account number {row['account_number']}")
# print(f"A/c balance is Rs.{self.balance}")
# break
# 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 ==1:
acct1.open_account()
if customer_visit ==2:
acct1.existing_holder()
holder_option = int(input())
if holder_option ==1:
acct1.deposit()

Related

How to compare 2 text files and print out a certain field of the correct file if the 2 files don't match-up in that specific line in python?

Here is my code so far. I am trying to make a system where a volunteer enters the data they have from counting coins and weighing the bag and it checks it. I then want to take that output and do math so the volunteer knows how many coins they need to take out or add to the bag.
import csv
import os.path
i = 0
accuracy = 0
incorrectBags = 0
correctBags = 0
def menu():
menuChoice = input("Menu: \n1) New Volunteer \n2) Check File Accuracy \n3) Check Overall Accuracy \n\nSelect an option: ")
if menuChoice == "1":
fileCheck()
elif menuChoice == "2":
accCheck()
elif menuChoice == "3":
allAccCheck()
def writeVolFile():
global f1
global volName
global volCoinType
global volBagWeight
with open(f"{volFile}", "w+") as f1:
volName = input("Input Volunteer Name: ")
volCoinType = input("Coin Types: \n £2 \n £1 \n 50p \n 20p \n 10p \n 5p \n 2p \n 1p \nInput your Coin Type (value only eg 5p = 0.5):")
volBagWeight = input("Input Bag Weight: ")
volAnswers = (volName, volCoinType, volBagWeight)
f1.write(",".join(volAnswers))
menu()
def fileCheck():
global volFile
volFile = input("Create your file by inputting Volunteer Name: ")
if os.path.exists(f"{volFile}"):
print("File already exists.")
fileCheck()
else:
writeVolFile()
def accCheck():
global accuracy
global correctBags
global incorrectBags
global i
global lines2
volFileName = input("What is the volunteer's name? ")
with open("coinweight.txt", "r") as f2, open(f"{volFileName}", "r") as f1:
for line1 in f1:
i += 1
for line2 in f2:
if line1 == line2:
print(f"Thank you for your help {volFileName}.")
accuracy+=1
correctBags+=1
else:
lines2 = f2.readlines
field = line2.split(",")
print(field[2])
accuracy-+1
incorrectBags-=1
menu()
# with open("coinweight.txt", "r") as f1:
# reader = csv.reader(f1)
# rowcount = 0
# for row in reader:
# rowcount = rowcount+1
# for field in row:
# if field == volCoinType:
# print("Found on row",rowcount)
# print(accuracy)
Here is what the coinweight.txt file looks like that has the correct values for the type of coin, coin weight and the bag weight.
2,12,120
1,8.75,175
0.5,8,160
0.2,5,250
0.1,6.5,325
0.05,2.35,235
0.2,7.12,356
0.1,3.56,356

Index error, can't seem to figure this one out

I am totally lost on what to do with this code. But im getting an error on the line
account.append(BankAccount(lst[0],lst[1],float(lst[2]),float(lst[3].replace('\n',''))))
can anyone help me with how to correct this?
Thank you!
FULL CODE:
class BankAccount: #BankAccount class implementation
def __init__(self, ID,PIN,checking,savings):
self.ID = ID
self.PIN = PIN
self.checking = checking
self.savings = savings
def getID(self):
return self.ID
def getPIN(self):
return self.PIN
def getSavings(self):
return self.savings
def getChecking(self):
return self.checking
def withdraw(self,amount,type): #withdraw method returns False if
if(type==1):
#amount is greater than savings balance
if(self.savings<amount):
return False
else: #else deducts amount from savings balance and returns True
self.savings -= amount
elif(type==2):
#amount is greater than savings balance
if(self.checking<amount):
return False
else:
self.checking -= amount
return True
def deposit(self,amount,type):
if(type==1):
self.savings += amount
elif(type==2):
self.checking += amount
def main():
account = []
n=0
with open("accounts.txt") as file: #reads data from file named accounts.txt
for line in file: #reads line by line from file
li = line.split(' ') #splits the line based on ' '
#creates an object of BankAccount and appends it to account list
account.append(BankAccount(li[0],li[1],float(li[2]),float(li[3].replace('\n',''))))
n += 1 #to keep track of number of accounts read from file
userid = input("Enter ID: ")
userpin = input("Enter PIN: ")
i=0
#loops through accounts and performs respective operations
while i<n:
if(account[i].getID()==userid):
if(account[i].getPIN()==userpin):
option = int(input('Enter 1 for withdraw 2 for transfer 3 for balance: '))
if(option==1):
type = int(input('Select type 1. Savings 2.checking: '))
amount = float(input("Enter amount: "))
if(account[i].withdraw(amount,type)):
if(type==1):
print(amount,'withdrawn. Closing balance: ',account[i].getSavings())
else:
print(amount,'withdrwan. Closing balance: ',account[i].getChecking())
else:
print('insufficient funds in your account')
elif(option==2):
option = int(input('Enter 1 for within account transfer 2 for other account: '))
if(option==1): #within account transfer
fromto = int(input('Enter 1. transfer from savings to checking 2. transfer from checking to savings: '))
amount = float(input('Enter amount: '))
if(fromto==1):
account[i].withdraw(amount,1)
account[i].deposit(amount,2)
print('Transfer successful from savings to checking')
else:
account[i].withdraw(amount,2)
account[i].deposit(amount,1)
print('Transfer successful from checking to savings')
else: #other account transfer
accID = input('Enter account ID to transfer money: ')
j=0
while j<n:
if(account[j].getID()==accID):
break
j += 1
if(j<n):
type = int(input('Select type 1. Savings 2.checking: '))
amount = float(input("enter amount: "))
account[i].withdraw(amount,type)
account[j].deposit(amount,type)
print('Transfer successful to account :',account[j].getID())
if(type==1):
print(amount,'transferred. Your savings balance: ',account[i].getSavings())
else:
print(amount,'transferred. Your checking balance: ',account[i].getChecking())
else:
print('Invalid account ID. Transfer of funds terminated.')
else:
type = int(input('Select type 1. Savings 2.checking: '))
if(type==1):
print('Your savings balance:',account[i].getSavings())
else:
print('Your checking balance:',account[i].getChecking())
break
i += 1
if(i==n): #if i reaches n then it's an invalid login
print('invalid login')
else: #writes the account details into the file accounts.txt
file = open('accounts.txt','w')
j=0
while j<n:
file.write(account[j].getID()+' '+account[j].getPIN()+' '+str(account[j].getChecking())+' '+str(account[j].getSavings())+' ')
j += 1
file.close() #closes file stream
print('Thank you!!')
main()
There is most likely a line with less than 4 elements in your accounts.txt file (possibly an empty line at the end).

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()

ValueError: not enough values to unpack (expected 3, got 2) & TypeError: must be str, not MemberClass

Below is my code for a class I am currently working. The title contains the errors I am receiving. Could someone please assist with my code? (The comment's explain the area of concern. Main Menu functions 5 & 6.)
PART 1 - CLASS ESTABLISHMENT
class MemberClass:
name = ""
phone = 0
number = 0
# Initiator Method
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
# Mutator Method 1
def set_name(self, name):
self.name = name
# Mutator Method 2
def set_phone(self, phone):
self.phone = phone
# Mutator Method 3
def set_number(self, number):
self.number = number
# Accessor Method 1
def get_name(self):
return self.name
# Accessor Method 2
def get_phone(self):
return self.phone
# Accessor Method 3
def get_number(self):
return self.number
# Display Method
def display_data(self):
print("")
print("Current Team Member's Information")
print("------------------------------------------------")
print("Member's Name: ", self.name)
print("Member's Phone Number: ", self.phone)
print("Member's Jersey Number: ", self.number)
print("------------------------------------------------")
PART 2 - PROGRAM FUNCTIONS AND DATA
# Create a function for the main menu
def print_menu():
print("===========Main Menu===========")
print("1. Display Current Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Progress.")
print("6. Load Current Team Roster")
print("9. Exit Program.\n")
return int(input("Please Enter Your Selection: "))
# Create a function for main menu option 1
def print_members(team_members):
if len(team_members) == 0:
print("No Current Team Members In Memory! Please Add All Team Members.")
else:
for x in team_members.keys():
team_members[x].display_data()
# Create a function for main menu option 2
def add_members(team_members):
new_name = input("Enter New Team Member's Name: ")
new_phone = int(input("Enter New Team Member's Phone Number: "))
new_number = int(input("Enter New Team Member's Jersey Number: "))
team_members[new_name] = MemberClass(new_name, new_phone, new_number)
return team_members
# Create a function for main menu option 3
def remove_members(team_members):
remove_name = input("Enter Existing Team Member's Name to Remove: ")
if remove_name in team_members:
del team_members[remove_name]
print("The Team Member ("+remove_name+") Is No Longer In Our Roster.")
else:
print("The Provided Name ("+remove_name+") Is Not Currently In Our Roster. Please Try Again.")
return team_members
# Create a function for main menu option 4
def edit_members(team_members):
original_name = input("Enter Existing Team Member's Name To Edit: ")
if original_name in team_members:
adjusted_name = input("Enter Existing Team Member's Updated Name: ")
adjusted_phone = int(input("Enter Existing Team Member's Updated Phone Number: "))
adjusted_number = int(input("Enter Existing Team Member's Updated Jersey Number: "))
del team_members[original_name]
team_members[original_name] = MemberClass(adjusted_name, adjusted_phone, adjusted_number)
else:
print("The Provided Name ("+original_name+") Is Not Currently In Our Roster. Please Try Again.")
return team_members
# Create a function for main menu option 5 ***PROBLEM AREA***
def save_members(members, filename):
out_file = open(filename, "wt")
with open(filename, "wt") as out_file:
for name, phone, number in members.items():
out_file.write(name + "," + phone + "," + number + "\n")
# Create a function for main menu option 6 ***PROBLEM AREA***
def load_members(members, filename):
in_file = open(filename, "rt")
with open(filename, "rt") as in_file:
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, phone, number = in_line.split(",")
members[name] = phone
PART 3 - PROGRAM ROOT CODE
# Team manager welcome screen, date & time
print("Welcome to San Angelo's Softball Team Roster")
print("This program keeps the most up-to-date information")
print("Today's Date: April 23, 2018")
print("Current Time: 0900\n")
# Create a dictionary named "team_members"
team_members = {}
# Provides Menu Screen
menu_selection = print_menu()
# Create while loop repeating the main menu.
while menu_selection != 9:
if menu_selection == 1:
print_members(team_members)
elif menu_selection == 2:
team_members = add_members(team_members)
elif menu_selection == 3:
team_members = remove_members(team_members)
elif menu_selection == 4:
team_members = edit_members(team_members)
elif menu_selection == 5:
filename = input("Enter Desired Filename: ")
save_members(team_members, filename)
elif menu_selection == 6:
filename = input("Enter Existing Filename: ")
load_members(team_members, filename)
menu_selection = print_menu()
print("Thank You For Updating San Angelo's Softball Team Roster!")
When you iterate a dictionary via dict.items, you may only iterate key / value pairs. Therefore, this line will fail as you are attempting to unpack 3 items when only 2 exist (key & value):
for name, phone, number in members.items():
Instead, what you should do:
for name, myclass in members.items():
phone = myclass.phone
number = myclass.number

Why are some variables not defined?

This is what I have to do:
Look up and print the student GPA
Add a new student to the class
Change the GPA of a student
Change the expected grade of a student
Print the data of all the students in a tabular format
Quit the program
import student
import pickle
lookup = 1
change = 2
add = 3
delete = 4
QUIT = 0
FILENAME = 'student.dat'
def main():
students_info = load_students()
choice = 0
load_students()
#add(students_info)
change_grade(students_info)
change_GPA(students_info)
#get_menu_choice()
look_up(students_info)
while choice != QUIT:
choice = get_menu_choice()
if choice == lookup:
look_up(students_info)
elif choice == add:
add(students_info)
elif choice == change:
change(students_info)
elif choice == delete:
delete(students_info)
save_students(students_info)
def load_students():
try:
input_file = open(FILENAME, 'rb')
students_dict = pickle.load(input_file)
input_file.close()
except IOError:
students_dict = {}
print(students_dict)
return students_dict
def get_menu_choice():
print()
print('Menu')
print("-------------------")
print('1. Look up ID')
print('2.....')
choice = int(input("Enter your choice:"))
return choice
def look_up(students_info):
ID = input('Enter ID:')
print(student_info.get(ID, "Not found!"))
## try:
## print(students_info[ID])
## except KeyError:
## print("Not found!")
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
GPA= float(input("New GPA:"))
students=student.Student(ID,GPA,grade,work)
students_info[ID] = students
print ("This",students_info[ID])
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
New_grade = input("Enter new grade:")
students=student.Student(ID,GPA,grade,work)
students_info[ID] = students
#new_grade = students_info[name]
else:
print("Not found!")
def add(students_info):
name = input("Enter the student name:")
ID= input("Enter student's ID:")
GPA= float(input("Enter GPA:"))
grade= input("Enter student's expected grade:")
work = input("Does the student work part time or full time?")
students=student.Student(name,ID,GPA,grade,work)
print(students_info['ID'])
def save_students(students_info):
output_file = open(FILENAME, 'wb')
pickle.dump(students_info, output_file)
output_file.close()
main()
Whenever I tried to change the GPA or grade it's not defined. How could I change one value from the dictionary studens_info?
As gus42 has commented, the errors you are getting are from the lines:
students=student.Student(ID,GPA,grade,work)
You've not defined grade or work in either of the places you do this (nor GPA in change_grade), so it should not be surprising that you're getting an error.
I think there are two ways to fix the issue:
The simplest way is to change your logic from creating a new Student object to modifying the one that already exists. I don't know exactly what the attribute names are in your Student class, but here's a reasonable guess at a solution:
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
GPA= float(input("New GPA:"))
students_info[ID].GPA = GPA # assign new GPA to old student object
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
grade = input("Enter new grade:")
students_info[ID].grade = grade # assign new grade to existing student object
else:
print("Not found!")
The other option is to replace the existing Student object with a new one with some different values. This is close to what your current code, but it only really makes sense if your Student objects are immutable (perhaps because you made the type with namedtuple?). To make it work (where your current code does not), you'll have to load the old values from the old Student object before making the new object:
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
new_GPA = float(input("New GPA:"))
old_grade = students_info[ID].grade # load old values
old_work = students_info[ID].work
new_student = students.Student(ID, new_GPA, old_grade, old_work)
students_info[ID] = new_student # replace the old student with a new object
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
new_grade = input("Enter new grade:")
old_GPA = students_info[ID].GPA
old_work = students_info[ID].work
new_student = students.Student(ID, old_GPA, new_grade, old_work)
students_info[ID] = new_student
else:
print("Not found!")

Categories

Resources