[Tutor] updating a Csv file

Albert-Jan Roskam fomcl at yahoo.com
Wed Oct 20 11:05:06 CEST 2010

Hi all,

How can I update a csv file? I've written the code below, but it does 
not work ("Error: line contains NULL byte"). I've never tried opening a 
file in read and write mode (r+) at the same time before, so I suspect 
that this is the culprit. Should I instead just open one file, write to 
another, throw away the original and rename the new file? That seems 

import csv, string

def updateLine(idVar, idValue, myCsv, newLine):

    f = open(myCsv, "r+")

    r = csv.reader(f)

    w = csv.writer(f)

    header = r.next()

    idPos = header.index(idVar)

    for row  in r:

        if row[idPos] == idValue:

            row = newLine



updateLine(idVar = "Id",

           idValue = "hawxgXvbfu",

           myCsv = "c:/temp/someCsv.csv",

           newLine = [ch for ch in string.letters[0:9]])




All right, but apart from the sanitation, the medicine, education, wine,
 public order, irrigation, roads, a fresh water system, and public 
health, what have the Romans ever done for us?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101020/32f7cf03/attachment.html>

More information about the Tutor mailing list