从DictReader写入CSV时出错

时间:2016-01-14 16:58:58

标签: python csv dictionary field writer

我有以下代码:

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

输出,如下:

 # 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'}

其中0填写以前缺少的字段。

如何将每一行写入CSV。我一直试图使用类似的东西。

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)

我收到错误!

sequence expected

我也试过使用DictWriter,但我不熟悉它。我是python的新手。无论如何只需将DictReader的结果行写入新的CSV?

1 个答案:

答案 0 :(得分:1)

您对DictWriter对象有所了解。

csv.DictWriter对象可用于从dict写入csv文件:

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

    csv_out.writeheader()

    for row in reader:
        csv_out.writerow(row)

替换从输入中读入的空白值:

# 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)
相关问题