[英]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. 其中0填充以前缺少的字段。
How do I go about writing each row of this out to a CSV. 我该如何将每一行写入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. 我也尝试使用DictWriter,但我并不熟悉。 I am very new to python. 我是python的新手。 is there anyway to simply write the resulting rows of the DictReader to a new CSV? 无论如何,是否可以将DictReader的结果行简单地写入新的CSV?
You're correct about the DictWriter
object. 您对DictWriter
对象是正确的。
The csv.DictWriter object can be used to write from a dict
to a csv
file: 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)
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.