So I've been attempting to use the csv module in Python to add data to existing rows and columns, but only specific columns of each row. So for examples let's say my existing csv file has the following:
id, name, city, age
1, Ed,, 34
2, Pat,, 23
So basically the city of each person is missing, so I would like to update each row with that person's city. However, the writerow method only seems replace the existing data within the csv file. Changing the open file to append mode just adds the data to a new row. Is there any way to skip the existing data, and only add the city to each row?
Thanks
Here's a post about another developer attempting to do something similar - updating specific records in a csv file - http://www.dreamincode.net/forums/topic/196479-editing-a-csv-file/
The code snippet in his post demonstrates how he searches for a particular 'position' (cell) in the csv file (like a specific cell in excel) and update that cell with new information. A city for a specific user in your case.
So emulating his example code, you could achieve your desired results.
However, if you see yourself doing this all the time - 'updating cells in a csv file', you are better off using a database to store the information. By importing the initial set of data from the initial csv and any further updates done via update calls to your chosen db. Use a library that provides an orm to interact with your database. :-)
Even sqlite3 will be better than trying to update specific cells in csv file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With