你走的路很好。你需要一个函数来更新你的文件,就像你读它一样。例如,我写过这样一个函数。给你: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)