Overwriting a specific row in a csv file using Python's CSV module

I will add to Steven Answer :

import csv

bottle_list = []

# Read all data from the csv file.
with open('a.csv', 'rb') as b:
    bottles = csv.reader(b)
    bottle_list.extend(bottles)

# data to override in the format {line_num_to_override:data_to_write}. 
line_to_override = {1:['e', 'c', 'd'] }

# Write data to the csv file and replace the lines in the line_to_override dict.
with open('a.csv', 'wb') as b:
    writer = csv.writer(b)
    for line, row in enumerate(bottle_list):
         data = line_to_override.get(line, row)
         writer.writerow(data)

You cannot overwrite a single row in the CSV file. You'll have to write all the rows you want to a new file and then rename it back to the original file name.

Your pattern of usage may fit a database better than a CSV file. Look into the sqlite3 module for a lightweight database.

Tags:

Python

Csv