I was wondering if there was a way to insert data into a specific cell of a csv file with python. Lets say I have the variable 'data' and it stores the value "300". How would I add that data to row 3 column 2 in a csv file? Thanks for all your help ahead of time and I appreciate any advice.
-
possible duplicate of [Writing to a particular cell using csv module in python](http://stackoverflow.com/questions/3699927/writing-to-a-particular-cell-using-csv-module-in-python) – rwflash Oct 10 '14 at 16:07
2 Answers
Suppose I have the following list of lists:
>>> data=[[1,2,3],
... [4,5,6],
... [7,8,9]]
You can change any item with data[row][col]
like so:
>>> data[1][0]="new value!"
>>> data
[[1, 2, 3], ['new value!', 5, 6], [7, 8, 9]]
When you write a csv file, you are usually writing a data structure that looks like a list of lists or a dict of lists. Just change the value of the row, col (in the case of a list of lists) or the header, value in the case of a dict prior to writing the data using csv
.
Consider, given this csv text file:
$ cat /tmp/f.csv
1,2,3
4,5,6
7,8,9
You can open the file and read it:
>>> with open('/tmp/f.csv') as f:
... data=[row for row in csv.reader(f)]
>>> data
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Now modify:
with open('/tmp/f.csv', 'w') as f:
w=csv.writer(f)
data[1][0]="New Value!"
for row in data:
w.writerow(row)
Then see that it has changed:
$ cat /tmp/f.csv
1,2,3
New Value!,5,6
7,8,9

- 98,345
- 23
- 131
- 206
-
I'm getting an error when reading the file (`with open`).. I pressed enter twice to return to python cursor and then `_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?` – James Oct 04 '16 at 23:38
In your example, we have a list object that is a Nested List.
To access the item that you want to replace in your NestedList, you would specify the x,y values :
nested_list [ x ] [ y ]
or in your example...
nested_list [ 3 ] [ 2 ]
So now that we know how to access the value that we want to replace, we can simply delete that item at column number 2, and then insert the new item at column number 2 like so :
del nested_list [ 3 ] [ 2 ] # Delete the Old Item
nested_list [ 3 ].insert ( 2 , "New Item Value" )
I prefer the above method over a one-liner like...
nested_list [ 3 ] [ 2 ] = "New Item Value"
Because I often run into immutability issues with python lists where the value does not actually change to the "New Item Value".
Deleting and Inserting has been a reliable list replacement method for me.

- 601
- 5
- 10