3

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.