你需要读入整个文件,处理它,然后写回整个文件。修改文件实际上是不可能的。在
通过指定参数分隔符是:,可以使用Python的csv库来帮助解析文件。通过这样做,每个条目都会自动作为参数列表读入,例如['12647859', 'Chips', '1.50', '50']import csv
stock_file = 'stock.csv'
stock = {}
with open(stock_file, 'rb') as f_stock:
csv_stock = csv.reader(f_stock, delimiter=':')
for cols in csv_stock:
stock[cols[0]] = cols
print stock
while True:
product_code = raw_input("Please enter product code: ")
product_quantity = int(raw_input("Please enter quantity: "))
try:
stock[product_code][3] = int(stock[product_code][3]) + product_quantity
break
except KeyError, e:
print "Unknown product ID, try again"
with open(stock_file, 'wb') as f_stock:
csv_stock