You will need to read the whole file in, process it, and then write the whole file back. Modifying a file is not really possible.
This could be done as follows using Python's csv
library to help parse the file, by specifying that the parameter delimiter is a :
. By doing this, each entry is automatically read in as a list of parameters e.g. ['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 = csv.writer(f_stock, delimiter=':')
csv_stock.writerows(stock.values())
So for the following input:
Please enter product code: 12345670
Please enter quantity: 1000
The stock file would be updated as follows:
12647859:Chips:1.50:50
11111115:Olives:1.50:100
16728769:Crisps:1.00:60
10928738:Raisins:0.75:100
19208114:Banana:0.50:75
30298712:Gluestick:1.99:50
12345670:Cadbury:0.50:1100
22222220:Blackberries:1.00:100
19832876:Cake:2.00:50
14054310:Phone:70.50:5
Note, as the entries are stored in a dictionary, the ordering is not maintained in the file. If this is required, then it can be converted to use an OrderedDict
Note, if you are not allowed to use the csv
library, it could be redone as follows:
stock_file = 'input.txt'
stock = {}
with open(stock_file, 'rb') as f_stock:
for line in f_stock:
cols = line.split(':')
stock[cols[0]] = [col.strip() for col in cols]
while True:
product_code = raw_input("Please enter product code: ")
product_quantity = int(raw_input("Please enter quantity: "))
try:
stock[product_code][3] = str(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:
f_stock.write('\n'.join(':'.join(line) for line in stock.values()))