写入csv我收到错误:_csv.Error:序列预期

时间:2016-01-16 00:45:21

标签: python python-2.7 csv

请帮忙。当我想将我的dict AllListInstance写入csv文件时,我收到错误。这是我的代码:

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

对我预期的输出的解释:

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

1 个答案:

答案 0 :(得分:1)

您传入单整数

len(AllListInstance[key])

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

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