Writing to a particular cell using csv module in python

The csv module provides facilities to read and write csv files but does not allow the modification specific cells in-place.

Even the csvwriter.writerow(row) method you highlight in your question does not allow you to identify and overwrite a specific row. Rather it writes the row parameter to the writer’s file object, in effect it simply appends a row the csv file associated with the writer.

Do not be dissuaded from using the csv module though, it is simple to use and with the primitives provided you could implement the higher level functionality you are looking for relatively easily.

For example take a look at the following csv file:

1,2,3,four,5
1,2,3,four,5
1,2,3,four,5

The word four is in column 3 (the fourth column but a row is just a list so the indexing is zero based), this can be easily updated to contain the digit 4 with the following program:

import csv
in_file = open("d:/in.csv", "rb")
reader = csv.reader(in_file)
out_file = open("d:/out.csv", "wb")
writer = csv.writer(out_file)
for row in reader:
    row[3] = 4
    writer.writerow(row)
in_file.close()    
out_file.close()

Resulting in the output:

1,2,3,4,5
1,2,3,4,5
1,2,3,4,5

Granted creating some generic function that allows specific rows and columns to be identified and updated is a little more work, but not much more as manipulating a csv file in Python is just manipulating a sequence of lists.

Leave a Comment