How to replace a value in specific cell of a csv file?
<p>I want to make a python script which has a counter that replaces the current value of a specific cell in a CSV file. </p>

<p>My code is : </p>

<pre><code>with open(ctlLst[-1], 'rb') as csvfile:
    csvReader = csv.reader(csvfile)
    csvReader.next()
    for row in csvReader:
        if row[6]&gt;counter:
        newCTLcount=int(row[6])-counter
        #need to replace cell row[6]
</code></pre>

<p>The file looks like this: </p>

<pre><code> InterfaceCode  InterfaceSeqID  OperatorCode    CreationDateTime    MintransactionDateTime  MaxtransactionDateTime  NoOfRows    ControlFileName DataFileName
201 1170    30  20161005 04:30:27   20161004 06:55:56   20161005 03:08:37   8696    CTL_TripEventAndAlert_30_20161004.CSV   TripEventAndAlert_30_20161004.CSV
</code></pre>

<p>In this example I need to replace the value of 8696 (on row 2 cell 6) with a new value (newCTLcount).</p>

<p>Most probably it's a good idea to write while reading/parsing to save memory</p>

<pre><code>with open('out.csv', 'wb') as outfile:
  with open(ctlLst[-1], 'rb') as csvfile:
    csvReader = csv.reader(csvfile)
    csvWriter = csv.writer(outfile)
    csvReader.next()
    for row in csvReader:
      row[6] = int(row[6]) # assumed as int
       if row[6] &gt; counter:
         row[6] -= counter
      outfile.writerow(row)
</code></pre>

<p>For Python 2 see <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> </p>

python csv