Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

1 Answer

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.

share|improve this answer
1  
Thanks for the answer. So from the look of the code there it really isn't updating each row but replacing it or writing over it. But maybe that is the only way to do it. Just seems like something so simple but I guess the csv module doesn't have the ability? –  wilbev Apr 15 '12 at 6:16
 
As far as I know, using csv module in a couple of projects, there's no concept of 'updating' a cell in a csv row using the python csv module. –  Calvin Cheng Apr 15 '12 at 8:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.