简体   繁体   中英

Error writing from DictReader into CSV

I have the following code:

def fillBlanks():

    # There are duplicate fields in the 'HEADERS' list. A better 'HEADERS' list might be:
    # HEADERS = ['ST', 'Year', 'PCT_SHORT', 'PCT_V_SHORT']
    HEADERS =['ST','Year','PCT_SHORT','PCT_V_SHORT','Year','PCT_SHORT','PCT_V_SHORT','Year','PCT_SHORT','PCT_V_SHORT' ]
    fileH = open(outputDir+"PCT_SHORT_V_SHORT.csv", 'rb')
    fileb = open(outputDir+"PCT_SHORT_V_SHOR.csv", 'wb')
    reader = csv.DictReader(fileH, HEADERS,restval=0)

    for row in reader:
      print row

It outputs, the following:

 # The `None` key is the result of the data row having more columns than the 'HEADERS' list has fields.
 {None: ['2012', '36', '12'], 'PCT_SHORT': '19', 'Year': '2013', 'PCT_V_SHORT': '17', 'ST': 'OK'}
 {'PCT_SHORT': 0, 'Year': 0, 'PCT_V_SHORT': 0, 'ST': 'AZ'}
 {None: ['2012', '14', '1'], 'PCT_SHORT': '24', 'Year': '2013', 'PCT_V_SHORT':  '2', 'ST': 'ID'}

where 0 fills in fields that were previously missing.

How do I go about writing each row of this out to a CSV. I have been trying to use something along the lines of.

with(fileb) as out:
  csv_out=csv.writer(out)

csv_out.writerow(['ST','Year','PCT_SHORT','PCT_V_SHORT','Year','PCT_SHORT','PCT_V_SHORT','Year','PCT_SHORT','PCT_V_SHORT','Year','PCT_SHORT','PCT_V_SHORT'])

for row in reader:
  csvwriters.writerow(row)

I get a Error!

sequence expected

I have also tried to use DictWriter, but I am not familiar with it. I am very new to python. is there anyway to simply write the resulting rows of the DictReader to a new CSV?

You're correct about the DictWriter object.

The csv.DictWriter object can be used to write from a dict to a csv file:

with(fileb) as csvfile:
    csv_out = csv.DictWriter(csvfile, fieldnames=HEADERS)

    csv_out.writeheader()

    for row in reader:
        csv_out.writerow(row)

To replace blank values read in from input:

# The names of the fields you want to check
fields = ['ST', 'Year']
# The value you want to replace a blank with. In this case, a 0
marker = 0

for row in reader:
    # Check the values, within this row, for each of the fields listed 
    for field_name in fields:
        field_value = str(row[field_name]).strip()

        row[field_name] = field_value or marker   

csv_out.writerow(row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM