Newbie question: replacing nulls in CSV with preceding value
Matt Waite
matt.waite at gmail.com
Thu Feb 1 17:31:00 EST 2007
Thanks everyone for your help. I got Skip's answer to work (mine is
pasted below):
import sys
import csv
last = {}
reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb"))
writer = csv.DictWriter(open("/home/mwaite/test/test3.csv", "wb"),
['ZONE','CITY','EVENT'], dialect='excel')
for row in reader:
for key in row:
if not row[key]:
row[key] = last.get(key, "")
writer.writerow(row)
last = row
On Feb 1, 3:37 pm, s... at pobox.com wrote:
> Matt> I have a CSV file, exported from Excel, that has blank records in
> Matt> it, and I need to fill them in with the values from the record
> Matt> just above it until it hits a non-blank value.
>
> Try something like:
>
> #!/usr/bin/env python
>
> import sys
> import csv
>
> last = {}
> reader = csv.DictReader(open("test1.csv", "rb"))
> writer = csv.DictWriter(open("test2.csv", "wb"),
> sys.stdout, fieldnames="Zone City Event".split())
> for row in reader:
> for key in row:
> if not row[key]:
> row[key] = last.get(key, "")
> writer.writerow(row)
> last = row
>
> Skip
More information about the Python-list
mailing list