首页 > 解决方案 > 减少文本文件列表中的数量

问题描述

如何从特定文本文件中选择项目。然后减少项目的数量并更新文本文件。

我试过这段代码。

def listingproductsbought(self):
    txtfile=open('user.txt','r')

文本文件例如是:

--------------------------------
|ItemID|itemName|Quantity|Price|
|------|--------|--------|-----|
|P1    |Dior    |441     |24   |
|------|--------|--------|-----|
|P2    |Elie    |411     |30   |
|------|--------|--------|-----|
|P3    |Gucci   |415     |41   |
|------|--------|--------|-----|
|P4    |Armani  |310     |20   |
|------|--------|--------|-----|
|P5    |Hermes  |805     |23   |
|------|--------|--------|-----|
|P6    |Hugo    |300     |32   |
|------|--------|--------|-----|
|P7    |Givenchy|490     |51   |
|------|--------|--------|-----|
|P8    |Byredo  |900     |13   |
|------|--------|--------|-----|
|P9    |Bvlgari |550     |42   |
|------|--------|--------|-----|
|P10   |Versace |649     |43   |
--------------------------------

我想选择一个产品,当我这样做时,项目数量(数量)会减少。

该文件的原始内容如下所示(根据问题的原始海报):

ItemID itemName Quantity Price 
P1 Dior 441 24 
P2 Elie 411 30 
P3 Gucci 415 41 
P4 Armani 310 20 
P5 Hermes 805 23 
P6 Hugo 300 32 
P7 Givenchy 490 51 
P8 Byredo 900 13 
P9 Bvlgari 550 42 
P10 Versace 649 43

标签: python

解决方案


使用纯 Python 代码(即没有外部库)

代码

def decrement_item(item_id, quantity):
    '''
        Decrement Quantity field based upon item_id
    
        inventory - file
        item_id   - item id to update
        quantity  - quantity to reduce by
    '''
    with open(inventory, 'r') as fin:
        # indexes for id and quantity
        index_id = 0
        index_quantity = 2
        
        # output buffer
        output = []
        
        # Add headaer to output buffer
        header = fin.readline().rstrip()
        output.append(header)  # header without '\n' at end of line
        
        bfound_item = False
        for line in fin:
            # Check each line for item_id then upadte quantity
            line = line.rstrip()
            if not bfound_item:
                # Only process if item_id has not been found yet
                # Break line into separate fields
                row = line.split()
                current_id = row[index_id]
                if current_id == item_id:
                    # Found item
                    # Check if sufficiente quantity
                    current_quantity = int(row[index_quantity])
                    if current_quantity >= quantity:
                        # Decrement quantity
                        current_quantity -= quantity
                        row[index_quantity] = str(current_quantity)
                        line = ' '.join(row)
                        bfound_item = True
                    else:
                        # Insufficient quantity for update
                        s = f"Sorry, available quantity is only {int(row[index_quantity])}"
                        raise Exception(s)
                    
            # Add line to output
            output.append(line)  # add copy since row changes with loop
            
    # Update inventory file
    with open(inventory, 'w') as fout:
        for line in output:
            fout.write(line + '\n')
   

测试

将 p4 中的数量减少 100 直到数量不足

while True:
    try:
        # keep updating quantity in P4 for
        # file inventory.txt until insufficient
        # amount remaining
        decrement_item("inventory.txt", "P4", 100)  # reduce P4 by 100
        
        # show updated inventory
        with open('inventory.txt', 'r') as fin:
            print('Contents of file inventory.txt')
            print(fin.read())
            
    except Exception as e:
        # Could not update
        print(e)
        break # Error during update
    

测试输出

Contents of file inventory.txt
itemID itemName Quantity Price
P1 Dior 441 24
P2 Elie 411 30
P3 Gucci 415 41
P4 Armani 210 20
P5 Hermes 805 23
P6 Hugo 300 32
P7 Givenchy 490 51
P8 Byredo 900 13
P9 Bvlgari 550 42
P10 Versace 649 43

Contents of file inventory.txt
itemID itemName Quantity Price
P1 Dior 441 24
P2 Elie 411 30
P3 Gucci 415 41
P4 Armani 110 20
P5 Hermes 805 23
P6 Hugo 300 32
P7 Givenchy 490 51
P8 Byredo 900 13
P9 Bvlgari 550 42
P10 Versace 649 43

Contents of file inventory.txt
itemID itemName Quantity Price
P1 Dior 441 24
P2 Elie 411 30
P3 Gucci 415 41
P4 Armani 10 20
P5 Hermes 805 23
P6 Hugo 300 32
P7 Givenchy 490 51
P8 Byredo 900 13
P9 Bvlgari 550 42
P10 Versace 649 43

Sorry, available quantity is only 10

推荐阅读