issues updating txt file in inventory program - python

I'm creating an invoice program that allows the user to select an item from a menu of products to either purchase or return. Once the user inputs the item ID and quantity desired, the program will read the inventory.txt file and write an UpdatedInventory.txt file, which will replace the inventory.txt file.
The inventory.txt file is formatted like this:
ID
item
stock
price
When my program runs, it does not print correctly on the UpdatedInventory.txt file. There's a lot of code here so bear with me.
As an aside, I feel like it would simplify the code if every purchase the user made was added into a list rather than hard coded. Thanks for the help!
Here's my main code:
import InventoryFile
import os
def readFile ():
#open the file and read the lines
inventoryFile = open ('Inventory.txt', 'r')
raw_data = inventoryFile.readlines ()
#remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip ('\n')
clean_data.append (clean_item)
#read lists into objects
all_objects = []
for i in range (0, len(clean_data), 4):
ID = clean_data [i]
item = clean_data [i+1]
qty = float (clean_data [i+2])
price = float (clean_data [i+3])
#create inventory object
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
all_objects.append (inventory_object)
return all_objects
def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print (item)
print ()
print ('Enter another item ID or 0 to stop')
def modify ():
found = False
search = -1
while search == -1:
search = input ('Enter the ID of the product you would like to purchase: ')
try:
if search == '0':
print ('The inventory has been updated...')
break
except Exception:
search = -1
print ('ERROR: Please enter a valid number.')
else:
inventoryFile = open ('inventory.txt', 'r')
temp_file = open ('UpdatedInventory.txt', 'w')
ID = str (inventoryFile.readline ())
while ID != '':
item = str (inventoryFile.readline ())
qty = float (inventoryFile.readline ())
price = float (inventoryFile.readline())
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
ID = ID.rstrip ('\n')
if ID == search:
purchase = -1
while purchase == -1:
purchaseEntry = float (input ('How many would you like to purchase? Negative numbers are returns'))
purchase = inventory_object.purchase (purchaseEntry)
if purchase is False:
purchase = -1
print ('ERROR: Insufficient stock!')
new_qty = inventory_object.restock (purchase)
transaction_object = InventoryFile.TransactionItem (ID, item, new_qty, price)
transaction_object.set_id (ID)
transaction_object.set_name (item)
transaction_object.set_qty (new_qty)
transaction_object.set_price (price)
ID = transaction_object.get_id ()
item = transaction_object.get_name ()
qty = transaction_object.get_qty ()
price = transaction_object.get_price ()
temp_file.write (ID + '\n')
temp_file.write (item + '\n')
temp_file.write (str (qty) + '\n')
temp_file.write (str (price) + '\n')
found = True
else:
temp_file.write (ID + '\n' )
temp_file.write (item + '\n')
temp_file.write (str (new_qty) + '\n')
temp_file.write (str (price) + '\n')
ID = inventoryFile.readline ()
if found:
print ('The file has been updated.')
else:
print ('That item was not found in the file.')
inventoryFile.close ()
temp_file.close ()
os.remove ('inventory.txt')
os.rename ('UpdatedInventory.txt', 'inventory.txt')
print ('Inventory has been updated.')
break
return search
def main ():
all_items = readFile ()
printMenu (all_items)
modify ()
main ()
Here's my Inventory Class file:
class Inventory ():
def __init__ (self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id (self):
return self.__id
def get_name (self):
return self.__name
def get_stock (self):
return self.__stock
def get_price (self):
return self.__price
def restock (self, new_stock):
if new_stock < 0:
print ('ERROR')
return False
else:
self.__stock += new_stock
return True
def purchase (self, purch_qty):
if self.__stock >= purch_qty:
self.__stock -= purch_qty
return self.__stock
else:
print ('ERROR: Insufficient stock')
return False
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__stock, '7.2f') + format (self.__price, '7.2f')
class TransactionItem (Inventory):
def __init__ (self, new_id, new_name, new_qty, new_price):
self.__qty = new_qty
Inventory.__init__(self, new_id, new_name, new_qty, new_price)
def get_id (self):
return self.__id
def set_id (self, new_id):
self.__id = new_id
def get_name (self):
return self.__name
def set_name (self, new_name):
self.__name = new_name
def get_qty (self):
return self.__qty
def set_qty (self, new_qty):
self.__qty = new_qty
def get_price (self):
return self.__price
def set_price (self, new_price):
self.__price = new_price
def calc_cost (self):
total = purch_qty * self.__price
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \
format (total, '7.2f')
Here is my inventory.txt file:
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
And here is what the updated inventory txt looks like after I input product ID 244, and purchase quantity of 5.
244
Large Cake Pan
4.0
19.99
576
Assorted Sprinkles
4.0
12.89
212
Deluxe Icing Set
4.0
37.97
827
Yellow Cake Mix
4.0
1.99
194
Cupcake Display Board
4.0
27.99
285
Bakery Boxes
4.0
8.59
736
Mixer
4.0
136.94

I've disabled TransactionItem. This seems to be working (I've combined the script files):
import os
class Inventory ():
def __init__(self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id(self):
return self.__id
def get_name(self):
return self.__name
def get_stock(self):
return self.__stock
def get_price(self):
return self.__price
def restock(self, new_stock):
if new_stock < 0:
print('ERROR')
return False
else:
self.__stock += new_stock
return True
def purchase(self, purch_qty):
if self.__stock >= purch_qty:
self.__stock -= purch_qty
return self.__stock
else:
print('ERROR: Insufficient stock')
return False
def __str__(self):
return self.__id + '\t' + self.__name + '\t' + \
format(self.__stock, '7.2f') + format(self.__price, '7.2f')
class TransactionItem (Inventory):
def __init__(self, new_id, new_name, new_qty, new_price):
self.__qty = new_qty
Inventory.__init__(self, new_id, new_name, new_qty, new_price)
def get_id(self):
return self.__id
def set_id(self, new_id):
self.__id = new_id
def get_name(self):
return self.__name
def set_name(self, new_name):
self.__name = new_name
def get_qty(self):
return self.__qty
def set_qty(self, new_qty):
self.__qty = new_qty
def get_price(self):
return self.__price
def set_price(self, new_price):
self.__price = new_price
def calc_cost(self):
self.total = purch_qty * self.__price
def __str__(self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \
format(self.total, '7.2f')
def readFile():
# open the file and read the lines
inventoryFile = open('Inventory.txt', 'r')
raw_data = inventoryFile.readlines()
# remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip('\n')
clean_data.append(clean_item)
# read lists into objects
all_objects = []
for i in range(0, len(clean_data), 4):
ID = clean_data[i]
item = clean_data[i + 1]
qty = float(clean_data[i + 2])
price = float(clean_data[i + 3])
# create inventory object
inventory_object = Inventory(ID, item, qty, price)
all_objects.append(inventory_object)
return all_objects
def printMenu(all_data):
print()
print('Select an item ID to purchase or return: ')
print()
print('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print(item)
print()
print('Enter another item ID or 0 to stop')
def modify():
found = False
search = -1
while search == -1:
search = input(
'Enter the ID of the product you would like to purchase: ')
try:
if search == '0':
print('The inventory has been updated...')
break
except Exception:
search = -1
print('ERROR: Please enter a valid number.')
else:
inventoryFile = open('inventory.txt', 'r')
temp_file = open('UpdatedInventory.txt', 'w')
ID = str(inventoryFile.readline())
while ID != '':
item = str(inventoryFile.readline())
qty = float(inventoryFile.readline())
price = float(inventoryFile.readline())
inventory_object = Inventory(ID, item, qty, price)
ID = ID.rstrip('\n')
item = item.rstrip('\n')
if ID == search:
purchase = -1
while purchase == -1:
purchaseEntry = float(
input('How many would you like to purchase? Negative numbers are returns'))
purchase = inventory_object.purchase(purchaseEntry)
if purchase is False:
purchase = -1
print('ERROR: Insufficient stock!')
#new_qty = inventory_object.restock(purchase)
#transaction_object = TransactionItem(
# ID, item, new_qty, price)
#transaction_object.set_id(ID)
#transaction_object.set_name(item)
#transaction_object.set_qty(new_qty)
#transaction_object.set_price(price)
#ID = transaction_object.get_id()
#item = transaction_object.get_name()
#qty = transaction_object.get_qty()
#price = transaction_object.get_price()
qty = inventory_object.get_stock()
price = inventory_object.get_price()
temp_file.write(ID + '\n')
temp_file.write(item + '\n')
temp_file.write(str(int(qty)) + '\n')
temp_file.write(str(price) + '\n')
found = True
else:
temp_file.write(ID + '\n')
temp_file.write(item + '\n')
temp_file.write(str(int(qty)) + '\n')
temp_file.write(str(price) + '\n')
ID = inventoryFile.readline()
if found:
print('The file has been updated.')
else:
print('That item was not found in the file.')
inventoryFile.close()
temp_file.close()
os.remove('inventory.txt')
os.rename('UpdatedInventory.txt', 'inventory.txt')
print('Inventory has been updated.')
break
return search
def main():
all_items = readFile()
printMenu(all_items)
modify()
main()
I hope it helps!

Have you tried stepping thru the program?
https://docs.python.org/2/library/pdb.html or https://docs.python.org/3/library/pdb.html
at some point you're losing information
(its hard to troubleshoot that big block of code sadly)

Related

How do I loop this function so that it keeps asking for the option rather than exiting the entire program every time I complete an option's task?

To give you some background info, I basically have to create 2 classes called ItemToPurchase that contains an item's name, quantity, description, and price. The other class ShoppingCart adds the item's name into a list with some other functions that modify the list. The part where I am facing some issues is at the part of execute_menu(). Let's say I enter the option 'a', after I give all the details of the item, the entire program ends. I do not want that. I want the program to ask me for the next option and keep asking me the next option after I complete a specific letter's required details.
class ItemToPurchase:
def __init__(self):
self.name = 'none'
self.quantity = 0
self.price = 0
self.description = 'none'
def item_name(self, name):
self.name = name
def item_price(self, price):
self.price = price
def item_quantity(self, quantity):
self.quantity = quantity
def item_description(self, description):
self.description = description
def print_item_cost(self):
print(self.name + " " + str(self.quantity) + " # $" + str(self.price) + " = $" + str(int(self.quantity) * int(self.price)))
def print_item_description(self):
print(self.name + ": " + self.description)
class ShoppingCart:
def __init__(self, name='none', date='January 1, 2016'):
self.customer_name = name
self.current_date = date
self.cart_items = []
def add_item(self, New_cart):
self.cart_items.append(New_cart)
def remove_item(self, item_name):
count = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
if item.name == item_name:
del self.cart_items[i]
count += 1
if count == 0:
print()
print('Item not found in cart. Nothing removed')
def modify_item(self, ItemToPurchase, Item_Name):
num = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
if Item_Name in [x.name for x in items]:
num += 1
if ItemToPurchase.description != "none":
item.item_description(ItemToPurchase.description)
if ItemToPurchase.price != 0:
item.item_price(ItemToPurchase.price)
if ItemToPurchase.quantity != 0:
item.item_quantity(ItemToPurchase.quantity)
if num == 0:
print()
print('Item not found in cart. Nothing modified.')
print()
def get_num_items_in_cart(self):
total_number = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
total_number += item.quantity
return total_number
def get_cost_of_cart(self):
total_cost = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
total_cost += int(item.quantity*item.price)
return total_cost
def print_total(self):
print(self.customer_name + "'s Shopping Cart - " + str(self.current_date))
count = len(self.cart_items) + 1
if len(self.cart_items) > 0:
print('Number of items:' + str(count))
print()
for i in self.cart_items:
i.print_item_cost()
total = self.get_cost_of_cart()
print()
print('Total:', str(total))
else:
print('SHOPPING CART IS EMPTY')
def print_descriptions(self):
if len(self.cart_items) > 0:
print(self.customer_name + "'s Shopping Cart - " + str(self.current_date))
print()
print('Item Descriptions')
for j in self.cart_items:
j.print_item_description()
else:
print('SHOPPING CART IS EMPTY')
def print_menu(cart):
print('MENU')
print('a - Add item to cart')
print('r - Remove item from cart')
print('c - Change item quantity')
print("i - Output items' descriptions")
print('o - Output shopping cart')
print('q - Quit')
**def execute_menu(option, Cart):
while option != 'q':
if option == 'o':
print('OUTPUT SHOPPING CART')
Cart.print_total()
break
elif option == 'i':
print("OUTPUT ITEMS' DESCRIPTIONS")
Cart.print_descriptions()
break
elif option == 'a':
print('ADD ITEM TO CART')
print('Enter the item name:')
itemName = input()
print('Enter the item description:')
itemDescrip = input()
print('Enter the item price:')
itemPrice = int(input())
print('Enter the item quantity:')
itemQuan = int(input())
New_cart = ItemToPurchase()
New_cart.name = itemName
New_cart.quantity = itemQuan
New_cart.price = itemPrice
New_cart.description = itemDescrip
Cart.add_item(New_cart)
break
elif option == 'r':
print('REMOVE ITEM FROM CART')
print('Enter name of item to remove:')
ItemName = input()
Cart.remove_item(ItemName)
break
elif option == 'c':
print('CHANGE ITEM QUANTITY:')
print('Enter the item name:')
Item_Name = input()
print('Enter the new quantity:')
Item_Quantity = int(input())
item_s = ItemToPurchase()
item_s.item_quantity(Item_Quantity)
Cart.modify_item(item_s, Item_Name)
break**
if __name__ == "__main__":
print("Enter customer's name:")
customer = input()
print("Enter today's date:")
date = input()
print()
print('Customer name:', customer)
print("Today's date:", date)
Cart = ShoppingCart(customer, date)
option = ''
print()
print_menu(Cart)
print()
print('Choose an option:')
option = input().lower().strip()
execute_menu(option, Cart)
The reason why I am adding the break is cause the program keeps printing the end print item infinit amount of times if I do not add the break.
Any help is appreciated. thank you and have a great day ahead!

Why do I cannot use __repr__ data outside of a class

I started Python and struggle on using __repr__ data outside of a class. Printing the data outputs a list with lists (exactly what I wanted to do), example:
print(test) leads to:
[['Food', '-10.15', '-15.89', '-50'], ['Clothing', '-25.55'], ['Auto', '-15']]
My problem is:
print(test[0]) leads to unexpected outputs, not:
['Food', '-10.15', '-15.89', '-50']
rather than some data like:
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
***********Clothing***********
Transfer from Food 50.00
-25.55
Total: 24.45
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
None
.***********Business***********
deposit 900.00
-10.99
class Category:
def __init__(self, category):
self.category = category
self.balance = 0
self.ledger = []
def __repr__(self):
b = []
b.append(self.category)
for obj in self.ledger:
if str(obj['amount'])[0] == "-":
b.append(str(obj['amount']))
return str(b)
def __str__(self):
lengthTop = int((30 - len(str(self.category))) / 2)
output = "*" * lengthTop + self.category + "*" * lengthTop
for entry in self.ledger:
if len(entry['description']) > 23:
x = slice(0, 23)
output += "\n" + entry['description'][x] + ("{:7.2f}".format(entry['amount']))
else:
output += ("\n" + entry['description'] + (" " * (23 - int(len(entry['description'])))) + ("{:7.2f}".format(entry['amount'])))
output += "\n" + "Total:" + ("{:7.2f}".format(self.balance))
return output
def check_funds(self, amount):
if amount > self.balance:
return False
else:
return True
def deposit(self, amount, description=""):
self.balance += amount
self.ledger.append({"amount": amount, "description": description})
def withdraw(self, amount, description=""):
if self.check_funds(amount) == True:
self.balance -= amount
self.ledger.append({"amount": -amount, "description": description})
return True
else:
return False
def get_balance(self):
return self.balance
def transfer(self, amount, newcategory):
if self.check_funds(amount) == True:
self.withdraw(amount, "Transfer to " + newcategory.category)
newcategory.deposit(amount, "Transfer from " + self.category)
return True
else:
return False
def create_spend_chart(categories):
test = categories
print(test)

Data comes out misaligned when printing list

I have a code that reads an inventory txt file that is suppose to display a menu for the user when it is run. However, when it runs the quantity and pice columns are misaligned:
Select an item ID to purchase or return:
ID Item Quantity Price
244 Large Cake Pan 7.00 19.99
576 Assorted Sprinkles 3.00 12.89
212 Deluxe Icing Set 6.00 37.97
827 Yellow Cake Mix 3.00 1.99
194 Cupcake Display Board 2.00 27.99
285 Bakery Boxes 7.00 8.59
736 Mixer 5.00 136.94
Enter another item ID or 0 to stop
Here is my code:
import InventoryFile
def readFile ():
#open the file and read the lines
inventoryFile = open ('Inventory.txt', 'r')
raw_data = inventoryFile.readlines ()
#remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip ('\n')
clean_data.append (clean_item)
#read lists into objects
all_objects = []
for i in range (0, len(clean_data), 4):
ID = clean_data [i]
item = clean_data [i+1]
qty = float (clean_data [i+2])
price = float (clean_data [i+3])
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
all_objects.append (inventory_object)
return all_objects
def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print (item)
print ()
print ('Enter another item ID or 0 to stop')
def main ():
all_items = readFile ()
printMenu (all_items)
main ()
How can I format the output so that the quantity and price columns are correctly aligned?
Here is the inventory class:
class Inventory:
def __init__ (self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id (self):
return self.__id
def get_name (self):
return self.__name
def get_stock (self):
return self.__stock
def get_price (self):
return self.__price
def restock (self, new_stock):
if new_stock < 0:
print ('ERROR')
return False
else:
self.__stock = self.__stock + new_stock
return True
def purchase (self, purch_qty):
if (new_stock - purch_qty < 0):
print ('ERROR')
return False
else:
self.__stock = self.__stock + purch_qty
return True
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__stock, '7.2f') + format (self.__price, '7.2f')
Using your class Inventory's getters you can make a list and just join the output.
def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
product_id = item.get_id()
product_name = item.get_name()
product_stock = item.get_stock()
product_price = item.get_price()
output = [product_id, product_name, product_stock, product_price]
output = [str(item) for item in output]
print('{:<5}\t{:<5}\t{:<5}\t{:<5}'.format(output))
print ()
print ('Enter another item ID or 0 to stop')

AttributeError: 'str' object has no attribute (function)

I'm trying to write an object-oriented program that allows me to enter and store monthly income and bills, and view all data as needed. I can successfully store an object, but when I try to use my view_all function, I get this error:
in view_all print(item.get_month())
AttributeError: 'str' object has no attribute 'get_month'
If you could help me track down this problem I'd be grateful!
# Create a month class
class Month:
# Use __init__ method to initialize the attributes
def __init__(self, month, income, tds, pnm, zia, water):
self.__month = month
self.__income = income
self.__tds = tds
self.__pnm = pnm
self.__zia = zia
self.__water = water
# The set methods accept arguments:
def set_month(self, month):
self.__month = month
def set_income(self, income):
self.__income = income
def set_tds(self, tds):
self.__tds = tds
def set_pnm(self, pnm):
self.__pnm = pnm
def set_zia(self, zia):
self.__zia = zia
def set_water(self, water):
self.__water = water
# The get methods return the data:
def get_month(self):
return self.__month
def get_income(self):
return self.__income
def get_tds(self):
return self.__tds
def get_pnm(self):
return self.__pnm
def get_zia(self):
return self.__zia
def get_water(self):
return self.__water
# The __str__ method return's the object's state as a string
def __str__(self):
return "Month: " + self.__month + \
"\nIncome: " + self.__income + \
"\nTDS: " + self.__tds + \
"\nPNM: " + self.__PNM + \
"\nZia: " + self.__zia + \
"\nWater: " + self.__water
And the main program:
import Month_Class
import pickle
ADD_MONTH = 1
VIEW_ALL = 2
QUIT = 3
FILENAME = 'ruidoso.dat'
def main():
months = load_months()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == ADD_MONTH:
add_month(months)
elif choice == VIEW_ALL:
view_all(months)
save_months(months)
def load_months():
try:
input_file = open(FILENAME, 'rb')
months_dct = pickle.load(input_file)
input_file.close
except IOError:
month_dct = {}
return month_dct
def get_menu_choice():
print()
print('Menu')
print('------------------')
print("1. Add data for a new month")
print("2. View data for all months")
print('Any other number saves and quits the program!')
print()
choice = int(input('Enter your choice: '))
while choice < ADD_MONTH or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def add_month(months):
month = input('Enter the name of the month: ')
income = input('Total income for this month: ')
tds = input('TDS Broadband bill total: ')
pnm = input('PNM bill total: ')
zia = input('Zia Natural Gas bill total: ')
water = input('City of Ruidoso bill total: ')
entry = Month_Class.Month(month, income, tds, pnm, zia, water)
if month not in months:
months[month] = entry
print('The entry has been added')
else:
print('That month already exists!')
def save_months(months):
output_file = open(FILENAME, 'wb')
pickle.dump(months, output_file)
output_file.close()
def view_all(months):
for item in months:
print(item.get_month())
print(item.get_income())
print(item.get_tds())
print(item.get_pnm())
print(item.get_zia())
print(item.get_water())
main()
You need to iterate over the dictionary differently
for month, item in months.items():
print(item.get_month())
...
In the view_all method, you must to iterate over dictionary:
for key, item in months.iteritems():
print(item.get_month())
and you got other error in __str__ method of Month class:
"\nPNM: " + self.__PNM + \
the correct is:
"\nPNM: " + self.__pnm + \

Trouble understanding with getting a unique instantiation in Python

I have an employee class which has an init method that reads an employees record in from a file. I also have an employees class which has an init_ method that attempts to read in all of the employee records.
I am having trouble with init for the employees class. Here is my code:
class EmployeeList():
records=[]
def __init__(self):
with open(database) as fp:
emp=employee(fp)
while (emp.id > 0):
print(emp)
self.records.append(emp)
emp=employee(fp)
The print(emp) is there for error checking, it shows that the records are being read in properly. When the EOF is reached, the init method for the employee sets the id to 0 and the name of the employee to "". I have two problems:
After the loop, all of the employees in employees.records are the same - id 0 and blanks for names. I am assuming that that emp is not creating a new instance each time it is called, and so all of the employees are being set to that one instance of emp, the very last one from when EOF is reached.
I doubt my code is "Pythonesque"; suggestions for improvement are welcome.
P.S. database is globally defined to the file name.
The entire code is here, sorry about the length:
class employee:
count = 0
def __init__(self,f=None):
if (f==None): # a user is inputting the employee
self.lastname = input("Employees last name:")
while type(self.lastname)!=type("1"):
print("Your input needs to be a name\n")
self.lastname = input("Employees last name:")
self.firstname = input("Employees first name:")
while type(self.firstname)!=type("1"):
print("Your input needs to be a name\n")
self.firstname = input("Employees first name:")
self.payrate = float(input("Employees pay rate:"))
while type(self.payrate)!=type(0.0):
print("Your input needs to be a pay rate\n")
self.payrate = float(input("Employees pay rate:"))
employee.count = employee.count + 1
self.id = employee.count
else: # the employee is being read in from the database and f is a file pointer
# read in an employee record and return false for end of file.
checkEOF = f.readline().rstrip('\r\n') #check for end of file
if (checkEOF != ""):
employee.id = int(checkEOF)
employee.firstname = f.readline().rstrip('\r\n')
employee.lastname = f.readline().rstrip('\r\n')
employee.payrate = float(f.readline().rstrip('\r\n'))
else:
employee.id = 0
employee.firstname = " "
employee.lastname = " "
employee.payrate = 0.0
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.id == other.id
return NotImplemented
def __str__(self):
return "Employee " + str(self.id) + " is "+self.firstname + " "+self.lastname+" and their pay rate is "+str(self.payrate)+"\n"
def __lt__(self, other):
if (self.lastname < other.lastname):
return True
elif (self.lastname > other.lastname):
return False
else: #same last names
if (self.firstname < other.firstname):
return True
elif (self.firstname > other.firstname):
return False
else: #same names
if (self.id < other.id):
return True
else: # note that ids cannot be the same
return False
def __gt__(self, other):
if (self.lastname > other.lastname):
return True
elif (self.lastname < other.lastname):
return False
else: # Same last names
if (self.firstname > other.firstname):
return True
elif (self.firstname > other.firstname):
return False
else: # Same names
if (self.id > other.id):
return True
else: # note that ids cannot be the same
return False
def payraise(self,payraise):
self.payrate = self.payrate+payraise
def saveemployee(self,fp):
fp.write(str(self.id)+"\n")
fp.write(self.firstname+"\n")
fp.write(self.lastname+"\n")
fp.write(str(self.payrate)+"\n")
class EmployeeList():
records=[]
def __init__(self):
with open(database) as fp:
emp=employee(fp)
while (emp.id > 0):
print(emp)
self.records.append(emp)
emp=employee(fp)
def __str__(self):
employeesprint = ""
for emp in self.records:
employeesprint = employeesprint + str(emp)
return employeesprint
def save(self):
self.records.sort()
with open(database,"w+") as fp:
fp.seek(0)
for emp in self.records:
emp.saveemployee(fp)
def menu():
print("\n")
print(choices[0]+". Add another employee")
print(choices[1]+". Print employees")
print(choices[len(choices)-1]+". Quit")
print("\n")
employees = EmployeeList()
choices = ["A","B","C"]
ch = "N"
while (ch != choices[len(choices)-1]):
menu()
ch=input("Make your choice ")
while not (ch in choices):
menu()
ch=input("Make your choice ")
if (ch == choices[0]):
employees.records.append(employee())
employees.save()
if (ch == choices[1]):
print(employees)
Sample output: You can see the two employees correctly being printed as they are read in:
Employee 1 is jane bob and their pay rate is 1.0
Employee 2 is jim bob and their pay rate is 3.4
A. Add another employee
B. Print employees
C. Quit
Make your choice B
Employee 0 is and their pay rate is 0.0
Employee 0 is and their pay rate is 0.0
your code:
if (checkEOF != ""):
employee.id = int(checkEOF)
employee.firstname = f.readline().rstrip('\r\n')
employee.lastname = f.readline().rstrip('\r\n')
employee.payrate = float(f.readline().rstrip('\r\n'))
else:
employee.id = 0
employee.firstname = " "
employee.lastname = " "
employee.payrate = 0.0
change 'employee' to 'self', 'employee' is the name of the class.

Categories