[Tutor] updating a Csv file

Dave Angel davea at ieee.org
Wed Oct 20 12:23:09 CEST 2010


  On 2:59 PM, Albert-Jan Roskam wrote:
> 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
> inefficient.
>
>
>
> 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
>              w.writerow(row)
>      f.close()
>
> updateLine(idVar = "Id",
>             idValue = "hawxgXvbfu",
>             myCsv = "c:/temp/someCsv.csv",
>             newLine = [ch for ch in string.letters[0:9]])
>
> Cheers!!
>
> Albert-Jan
>
In general, you don't want to update anything in place, unless the new 
items are guaranteed to be the same size as the old.  So when you're 
looping through a list, if you replace one item with another, no 
problem, but if you insert or delete, then you should be doing it on a copy.

In the file, the byte is your unit of measure.  So if what you're 
writing might be a different size (smaller or larger), then don't do it 
in place.  You may not be able to anyway, if the csv module can't handle 
it.  For example, the file object 'f' has a position, which is set by 
either read or write.  csv may assume that they can count on that 
position not changing from outside influences, in which case even 
same-size updates could fail.

DaveA





More information about the Tutor mailing list