gpt4 book ai didi

python - 从 DictReader 写入 CSV 时出错

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:35 25 4
gpt4 key购买 nike

我有以下代码:

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?

最佳答案

您对 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)

关于python - 从 DictReader 写入 CSV 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34795360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com