sagar sagar - 1 year ago 112
Python Question

Writing to a particular cell using csv module in python

I have to write a value to a particular cell (say the 8th cell) in my csv file.
I can see there is a

method to write an entire row, but I am not seeing anything to write a value to a particular cell.

Answer Source

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:


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

Resulting in the output:


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.