在库存程序中更新txt文件的问题

时间:2017-05-09 16:20:00

标签: python readfile writefile

我创建了一个发票程序,允许用户从产品菜单中选择要购买或退货的商品。一旦用户输入了所需的项目ID和数量,程序将读取inventory.txt文件并写入UpdatedInventory.txt文件,该文件将替换inventory.txt文件。 inventory.txt文件的格式如下:

ID
item
stock
price

当我的程序运行时,它无法在UpdatedInventory.txt文件上正确打印。这里有很多代码,所以请耐心等待。

顺便说一下,如果用户制作的每笔购买都添加到列表而不是硬编码中,我觉得它会简化代码。谢谢你的帮助!

这是我的主要代码:

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

这是我的库存类文件:

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

这是我的inventory.txt文件:

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

以下是输入产品ID 244,购买数量为5后更新后的库存txt的样子。

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

2 个答案:

答案 0 :(得分:0)

您是否尝试过程序? https://docs.python.org/2/library/pdb.htmlhttps://docs.python.org/3/library/pdb.html

在某些时候你会丢失信息

(遗憾的是很难解决这一大块代码)

答案 1 :(得分:0)

我已停用TransactionItem。这似乎有效(我已经合并了脚本文件):

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

我希望它有所帮助!