如何附加文件并取出特定的行python 3

时间:2016-01-21 22:01:58

标签: python file python-3.x dictionary append

我有一个格式为的库存文件:

12345678,Fridge,1,50
23456789,Car,2,50
34567890,TV,20,50

这是代码:

def main():
products = {}
#This is the file directory being made.
f = open('stockfile.txt') 
#This is my file being opened.

for line in f:


    # Need to strip to eliminate end of line character
    line = line[:-1]
    #This gets rid of the character which shows and end of line '\n'
    row = line.split(',')
    #The row is split by the comma
    products[row[0]] = [row[1], row[2],row[3]]
    #The products are equal to row 1 and row 2 and row 3. The GTIN is going to take the values of the product and price so GTIN 12345678 is going to correspond to Fridge and 1.

print(products)
total = 0

print('Id       Description         Total')
while True:
    GTIN = input('Please input GTIN ')
    if(GTIN not in products):
        print('Sorry your code was invalid, try again:')
        break

    row = products[GTIN]
    print(GTIN)
    description = row[0]
    value = row[1]
    stock = row[2]
    print(stock)

    quantity = input('Please also input your quantity required: ')
    row[2]= int(stock) - int(quantity)
    products[row[2]] = row[2]
    product_total= (int(quantity)*int(value))
    New_Stock  = GTIN + ',' + description + ',' + value + ',' + str(products[row[2]])
    f = open('stockfile.txt','r')
    lines = f.readlines()
    f.close()
    f = open("stockfile.txt","a")
    for row in lines:
        if((row + '\n') != (New_Stock + '\n')):
            f.write(New_Stock)
            f.close()

    print('%20s%20s%20s' % (GTIN, description, product_total))

    total = total + product_total

print('Total of the order is £%s' % total)
print(products)
main()

但是,代码不会更新股票。它应该做的是摆脱以前的产品库存,然后根据用户刚购买的数量进行更新。

我还没有完成它但是一旦库存达到零,我需要我的代码然后告诉用户我们已经缺货并需要一些新的库存。然后需要向用户发出消息,等待我们重新进货,然后再显示重新进货的价格。

如果你有时间,那么你能不能制作这些新的代码,但如果没有,你能解释一下如何更新库存以及我的代码无效的原因,谢谢。

5 个答案:

答案 0 :(得分:0)

在前几行中,您将整个数据文件加载到内存中:

stampAll(Map<String, Object>)

然后只需更新内存中的数据,让用户输入一个特殊的命令:&#34; save&#34;将整个列表写入您的文件。

您还可以捕获您的申请流程KILL信号,因此如果用户点击ctrl + c,您可以在退出前询问他是否要保存。

并且可能每隔几秒就将列表的临时副本保存到文件中。

答案 1 :(得分:0)

如果您的客户打算多次运行此程序,我建议您使用shelve模块。将整个文件读入内存并将其重新编写为文本将随着库存的增长而变得低效。 Shelve在您的PC上创建持久文件(确切地说是3个文件)以存储您的数据。最重要的是,shelve会为您提供所需的dict接口,因此您只需在文件上调用shelve.open()即可开始使用GTIN访问/更新您的库存作为钥匙。它非常简单,只需看看python手册。如果你真的想要一个文本文件,你可以拥有你的程序,遍历包含你的股票的shelve文件(与字典相同)和写入密钥(GTIN)及其值(你的股票数量)到文本你打开的档案。这样,您可以轻松直观地访问记录,也可以在TXT文件中使用可读格式。

答案 2 :(得分:0)

上面使用搁置的建议听起来是个好主意,但如果你想保留你的文件,但只使用(大部分)代码更新更改的记录(而不是每次都重写整个文件),这似乎有效。

def main():
    products = {}
    product_location  = {}
    location = 0
    # This is the file directory being made.
    with open('stockfile.txt', 'r+') as f:
        # This is my file being opened.

        for line in f:
            # keep track of each products location in file  to overwrite with New_Stock
            product_location[line.split(',')[0]] = location
            location += len(line)
            # Need to strip to eliminate end of line character
            line = line[:-1]
            # The row is split by the comma
            row = line.split(',')
            products[row[0]] = [row[1], row[2], row[3]]
            """
            The products are equal to row 1 and row 2 and row 3. The GTIN is going to take the values of the product and
            price so GTIN 12345678 is going to correspond to Fridge and 1.
            """

        print(sorted(products.items()))
        total = 0

        while True:
            GTIN = input('\nPlease input GTIN or press [Enter] to quit:\n')
            # To terminate user input, they just need to press ENTER
            if GTIN == "":
                break
            if (GTIN not in products):
                # Let the user continue with order after mistake in GTIN input
                print('Sorry your code was invalid, try again:')
                continue

            row = products[GTIN]
            print('GTIN:', GTIN)
            description = row[0]
            value = row[1]
            stock = row[2]
            stock_length = len(row[2])
            backorder = 0
            print('In Stock:', stock)

            quantity = input('Please also input your quantity required:\n')
            if int(quantity) > int(stock):
                row[2] = 0
                backorder = int(quantity) - int(stock)
                # TO DO
                Backordered_Stock = GTIN + ',' + description + ',' + value + ',' + str(backorder) + '\n'
            else:
                row[2] = int(stock) - int(quantity)
            products[row[2]] = row[2]
            product_total = (int(quantity) * int(value))
            New_Stock = GTIN + ',' + description + ',' + value + ',' + str(products[row[2]]).rjust(stock_length) + '\n'
            f.seek(product_location[GTIN])
            f.write(New_Stock)
            print('Ordered - {0:>6} GTIN: {1:>10}  Desc: {2:<20}  at £{3:>6}  Total value: £{4:>6}  On backorder: {5:>4}'.
                format(int(quantity), GTIN, description, int(value), product_total, backorder))

            total = total + product_total

        print('Total of the order is £%s' % total)

main()

答案 3 :(得分:0)

当您seek到指定行并致电write时,为了完全覆盖该行,而不影响其他行或无意中创建新行,您的库存中的每一行必须具有固定宽度。你如何确保固定宽度?通过为记录中的每个字段提供固定的宽度。基本上,您可以选择每个字段可以拥有的最大字符数;在这里我假设所有领域都是8(尽管它们不一定都是相同的),所以你的股票将以这种方式存储:

12344848,  Fridge,       2,      50
13738389,      TV,       5,      70

如果你继续这样做,每条线都有一个最大宽度,这将使你能够寻找线的起点并完全覆盖它。试试这段代码:

MAX_FIELD_LEN = 8

def main():
    products = {}
    product_location  = {}
    location = 0
    # This is the file directory being made.
    with open('stockfile.txt', 'r+') as f:
        # This is my file being opened.

        for line in f:
            # keep track of each products location in file  to overwrite with New_Stock
            product_location[line.split(',')[0]] = location
            location += len(line)
            # Need to strip to eliminate end of line character
            line = line[:-1]
            # This gets rid of the character which shows and end of line '\n'
            row = line.split(',')
            # The row is split by the comma
            products[row[0]] = [row[1], row[2], row[3]]
            # The products are equal to row 1 and row 2 and row 3. The GTIN is going to take the values of the product and price so GTIN 12345678 is going to correspond to Fridge and 1.

        print(products)
        total = 0

        while True:
            GTIN = input('Please input GTIN: ')
            # To terminate user input, they just need to press ENTER
            if GTIN == "":
                break
            if (GTIN not in products):
                print('Sorry your code was invalid, try again:')
                break

            row = products[GTIN]
            description, value, stock = row
            print('Stock data: ')
            print('GTIN \t\tDesc. \t\tStock \t\tValue')
            print(GTIN,'\t',description,'\t', stock, '\t', value)

            quantity = input('Please also input your quantity required: ')
            row[2] = str(int(stock) - int(quantity))
            product_total = int(quantity) * int(value)
            for i in range(len(row)):  
                row[i]  = row[i].rjust(MAX_FIELD_LEN)
            New_Stock = GTIN.rjust(MAX_FIELD_LEN) + ',' + ','.join(row) + '\n'
            #print(New_Stock, len(New_Stock))
            f.seek(product_location[GTIN])
            f.write(New_Stock)
            print('You bought: {0} {1} \nCost: {2}'.format(GTIN, description, product_total))

            total = total + product_total
        f.close()
        print('Total of the order is £%s' % total)

main()

使用此程序时,请确保TXT文件中的每个字段正好是8个字符宽(不包括逗号)。如果要增加字段宽度,请相应地更改MAX_FIELD_LEN变量。您的TXT文件应如下所示:

TXT FILE

答案 4 :(得分:0)

MAX_FIELD_LEN = 8

def main():
    products = {}
    product_location  = {}
    location = 0
    # This is the file directory being made.
    with open('stockfile.txt', 'r+') as f:
    # This is my file being opened.

    for line in f:
        # keep track of each products location in file  to overwrite with New_Stock
        product_location[line.split(',')[0]] = location
        location += len(line)
        # Need to strip to eliminate end of line character
        line = line[:-1]
        # This gets rid of the character which shows and end of line '\n'
        row = line.split(',')
        # The row is split by the comma
        products[row[0]] = [row[1], row[2], row[3]]
        # The products are equal to row 1 and row 2 and row 3. The GTIN is going to take the values of the product and price so GTIN 12345678 is going to correspond to Fridge and 1.

    print(products)
    total = 0

    while True:
        GTIN = input('Please input GTIN: ')
        # To terminate user input, they just need to press ENTER
        if GTIN == "":
            break
        if (GTIN not in products):
            print('Sorry your code was invalid, try again:')
            break

        row = products[GTIN]
        description, value, stock = row
        print('Stock data: ')
        print('GTIN \t\tDesc. \t\tStock \t\tValue')
        print(GTIN,'\t',description,'\t', stock, '\t', value)

        quantity = input('Please also input your quantity required: ')
        row[2] = str(int(stock) - int(quantity))
        product_total = int(quantity) * int(value)
        for i in range(len(row)):  
            row[i]  = row[i].rjust(MAX_FIELD_LEN)
        New_Stock = GTIN.rjust(MAX_FIELD_LEN) + ',' + ','.join(row) + '\n'
        #print(New_Stock, len(New_Stock))
        f.seek(product_location[GTIN])
        f.write(New_Stock)
        print('You bought: {0} {1} \nCost: {2}'.format(GTIN, description, product_total))

        total = total + product_total
    f.close()
    print('Total of the order is £%s' % total)

main()

这是文本文件:     12345678, Fridge, 1, 50 23456789, Car, 2, 50 34567890, TV, 20, 50

我在Mac桌面上执行此操作是否有所不同,或者它是python 3.4.3?