您將需要讀取整個文件,進行處理,然後寫回整個文件。修改一個文件是不可能的。
這可以通過使用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 = csv.writer(f_stock, delimiter=':')
csv_stock.writerows(stock.values())
所以以下輸入:
Please enter product code: 12345670
Please enter quantity: 1000
該股文件將被更新如下:
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
注意,作爲條目存儲在字典中,訂貨不在文件中維護。如果這是必需的,那麼它可以被轉換爲使用OrderedDict
注意,如果你不能使用csv
庫,它可以被重新進行如下:
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()))
你怎麼樣寫文件? – Andy
使用「w」方法 –
可能重複[你如何追加到Python中的文件?](http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file- in-python) – Andy