写入csv时出现错误:_csv.Error:预期序列 [英] Write to csv and I get error : _csv.Error: sequence expected

查看:149
本文介绍了写入csv时出现错误:_csv.Error:预期序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助.当我想将我的字典AllListInstance写到csv文件时出现错误.这是我的代码:

Please help. I get an error when I want to write my dict AllListInstance to csv file. This is my code:

AllListInstance= {frozenset(['OFFENSE INVOLVING CHILDREN']): [(95,), (96,), (35,), (80,), (100,)], frozenset(['BATTERY', 'THEFT']): [(173, 209), (173, 224)]}

with open('test1.csv', 'wb') as csv_file:
   for key in AllListInstance.keys():
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(len(AllListInstance[key]))
    for y in range(len(key)):
        csv_writer.writerow([x[y] for x in key])
        csv_writer.writerow(x[y] for x in AllListInstance[key])

预期输出:

5   # len(AllListInstance["OFFENSE INVOLVING CHILDREN"]) count of member
OFFENSE INVOLVING CHILDREN
95
96
35
80
100
2 # len(AllListInstance['BATTERY','THIEF']) count of member
BATTERY        THIEF
173            209
173            224

错误:

    csv_writer.writerow(len(AllListInstance[key]))
_csv.Error: sequence expected

我预期的输出解决方案:

Solusion for my expected ouput:

with open('test8.csv', 'wb') as csv_file:
  for key in AllListInstance.keys():
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow([len(key),len(AllListInstance[key])])
    csv_writer.writerow(list(key))
    for x in AllListInstance[key]:
        csv_writer.writerow(list(x))

推荐答案

您传入的是单个整数:

len(AllListInstance[key])

这不是序列,这是csv_writer.writerow()所期望的.如果要用长度值写一列,请将其包装在列表中:

That's not a sequence, which is what csv_writer.writerow() expects. If you want to write one column with the length value, wrap that in a list:

csv_writer.writerow([len(AllListInstance[key])])

这篇关于写入csv时出现错误:_csv.Error:预期序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆