【发布时间】:2016-04-28 08:56:15
【问题描述】:
我有一个格式如下的股票文件:
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()
但是,代码不会更新股票。它应该做的是摆脱之前给定产品的库存,然后根据用户刚刚购买的数量进行更新。
我还没有开始,但是一旦库存达到零,我需要我的代码告诉用户我们已经缺货并需要一些新库存。然后需要向用户发送一条消息,等待我们补货,然后再显示补货价格。
如果您有时间,请您也编写这段新代码,如果没有,您能否解释一下如何更新库存以及为什么我的代码不起作用,谢谢。
【问题讨论】:
标签: python file python-3.x dictionary append