11

I'm using Python's csv module to do some reading and writing of csv files.

I've got the reading fine and appending to the csv fine, but I want to be able to overwrite a specific row in the csv.

For reference, here's my reading and then writing code to append:

    #reading
    b = open("bottles.csv", "rb")
    bottles = csv.reader(b)
    bottle_list = []
    bottle_list.extend(bottles)
    b.close()

    #appending
    b=open('bottles.csv','a')
    writer = csv.writer(b)
    writer.writerow([bottle,emptyButtonCount,100, img])
    b.close()

And I'm using basically the same for the overwrite mode(which isn't correct, it just overwrites the whole csv file):

    b=open('bottles.csv','wb')
    writer = csv.writer(b)
    writer.writerow([bottle,btlnum,100,img])
    b.close()

In the second case, how do I tell Python I need a specific row overwritten? I've scoured Gogle and other stackoverflow posts to no avail. I assume my limited programming knowledge is to blame rather than Google.

William Wallace
  • 113
  • 1
  • 1
  • 4

2 Answers2

21

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)
Community
  • 1
  • 1
mouad
  • 67,571
  • 18
  • 114
  • 106
5

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.

Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • Thanks for the tip! I'm looking into the sqlite3 documentation now. I'll likely use it if I have more data to throw around. Right now singularity's solution is fine because my csv file isn't too big. – William Wallace Nov 11 '10 at 13:39