Inserting values ​​into specific cells in csv using python

I was wondering if there is a way to insert data into a specific cell of a csv file using python. Let's say I have a variable called "data" and it stores the value "300". How would I add this data to row 3 column 2 in a csv file? Thanks for your help in advance and I appreciate any advice.


source to share

2 answers

Suppose I have the following list of lists:

>>> data=[[1,2,3],
...       [4,5,6],
...       [7,8,9]]


You can change any element with the data[row][col]


>>> data[1][0]="new value!"
>>> data
[[1, 2, 3], ['new value!', 5, 6], [7, 8, 9]]


When you write a csv file, you usually write a data structure that looks like a list of lists or a list of lists. Just change the value of the string, col (in the case of a list of lists) or header, the value in the case of a dict, before writing the data with csv


Consider, given this csv text file:

$ cat /tmp/f.csv


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 change:

with open('/tmp/f.csv', 'w') as f:
    data[1][0]="New Value!"
    for row in data:


Then see what it changed:

$ cat /tmp/f.csv
New Value!,5,6




In your example, we have a list object that is a nested list.

To access the element you want to replace in your NestedList, you must provide 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 in column number 2, and then insert a new item at column number 2 like this:

    del nested_list [ 3 ] [ 2 ]   # Delete the Old Item
    nested_list [ 3 ].insert ( 2 , "New Item Value" )


I prefer the above method over one layer like ...

    nested_list [ 3 ] [ 2 ] = "New Item Value"


Because I often run into immutability issues with python lists where the value doesn't actually change to "new item value".

Deleting and inserting has been a reliable method of replacing lists for me.



All Articles