Search code examples
pythonreadfilewritefile

issues updating txt file in inventory program


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

Solution

  • 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!