我正在用Python编写自动售货机模拟作为学校作业,我需要编辑一个特定的行以保持库存清单的最新状态。
以下是代码:
import csv
with open('stock.csv','r') as STOCK_READ: #Counts the amount of items in the CSV file
ITEM_COUNT = 0
reader = csv.reader(STOCK_READ)
for line in reader:
ITEM_COUNT = ITEM_COUNT + 1
def GET_STOCK_COUNT():
with open('stock.csv', 'r') as STOCK_READ:
reader = csv.reader(STOCK_READ)
for line in reader:
print("{0} - {1} - {2} in stock".format(line[0],line[1],line[2]))
while True:
GET_STOCK_COUNT()
CHOSEN_ITEM = int(input("Input number of desired item: "))
这是CSV(它是:项目编号,名称,股票):
1,Coca Cola,10
2,Monster,10
3,Monster Ultra,10
通过让用户选择号码,我想让CSV编写器转到正确的行并在最后更改数字。
答案 0 :(得分:0)
这是使用字典的好地方。如果在GET_STOCK_COUNT函数中将数据保存到字典中,然后返回字典,则可以访问该字典,然后根据需要修改数据。
def GET_STOCK_COUNT():
stock = {}
with open('stock.csv', 'r') as STOCK_READ:
reader = csv.reader(STOCK_READ)
for line in reader:
stock[line[0]] = {
'name': line[1],
'stock': line[2],
}
return stock
这将允许您通过股票指数编号引用项目。 例如,如果您想更改订单项的库存,则可以执行以下操作:
stock = GET_STOCK_COUNT()
stock[CHOSEN_ITEM]['stock'] = new_value
您需要编写一个新功能来打印您的库存清单,但现在您可以访问这些数据,这样仍然可以。
答案 1 :(得分:0)
你走的很好。您需要一个函数来更新您的文件,就像您阅读它一样。我已经写了这样一个函数。你走了:
import csv
with open('stock.csv','r') as STOCK_READ: #Counts the amount of items in the CSV file
ITEM_COUNT = 0
reader = csv.reader(STOCK_READ)
for line in reader:
ITEM_COUNT = ITEM_COUNT + 1
def GET_STOCK_COUNT():
with open('stock.csv', 'r') as STOCK_READ:
reader = csv.reader(STOCK_READ)
for line in reader:
print("{0} - {1} - {2} in stock".format(line[0],line[1],line[2]))
def UPDATE_STOCK_COUNT(item_id):
with open('stock.csv', 'r') as STOCK_READ:
reader = csv.reader(STOCK_READ)
output = []
for line in reader:
if line[0] == item_id:
line[2] = str(int(line[2])-1)
output.append(line)
with open('stock.csv', 'w', newline='') as STOCK_WRITE:
writer = csv.writer(STOCK_WRITE)
writer.writerows(output)
while True:
GET_STOCK_COUNT()
CHOSEN_ITEM = input("Input number of desired item: ")
UPDATE_STOCK_COUNT(CHOSEN_ITEM)