 <p>All the occurances of <code>stocklevel</code> are getting replaced with the value of <code>newlevel</code> as you are calling <code>s.replace (stocklevel ,newlevel)</code>.</p> <blockquote> <p><strong>string.replace(s, old, new[, maxreplace]):</strong> Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.</p> </blockquote> <p><a href="https://docs.python.org/2/library/string.html" rel="nofollow">source</a></p> <p>As you suggested, you need to get the <code>code</code> and use it replace the stock level. </p> <p>This is a sample script which takes the 8 digit code and the new stock level as the command line arguments adn replaces it:</p> <pre><code>import sys import re code = sys.argv[1] newval= int(sys.argv[2]) f=open("stockcontrol.csv") data=f.readlines() print data for i,line in enumerate(data): if re.search('%s,\d+'%code,line): # search for the line with 8-digit code data[i] = '%s,%d\n'%(code,newval) # replace the stock value with new value in the same line f.close() f=open("in.csv","w") f.write("".join(data)) print data f.close() </code></pre> <p>Another solution using the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv</a> module of Python:</p> <pre><code>import sys import csv data=[] code = sys.argv[1] newval= int(sys.argv[2]) f=open("stockcontrol.csv") reader=csv.DictReader(f,fieldnames=['code','level']) for line in reader: if line['code'] == code: line['level']= newval data.append('%s,%s'%(line['code'],line['level'])) f.close() f=open("stockcontrol.csv","w") f.write("\n".join(data)) f.close() </code></pre> <p><strong>Warning:</strong> Keep a back up of the input file while trying out these scripts as they overwrite the input file.</p> <p>If you save the script in a file called <code>test.py</code> then invoke it as:</p> <p><code>python test.py 34512340 10</code>.</p> <p>This should replace the stockvalue of code 34512340 to 10.</p>