Python: 3.x
嗨。我有下面的csv文件,它有标题和行。行数可能因文件而异。我正在尝试将此csv转换为dict格式,第一行的数据正在重复
"cdrRecordType","globalCallID_callManagerId","globalCallID_callId"
1,3,9294899
1,3,9294933
Code:
parserd_list = []
output_dict = {}
with open("files\\CUCMdummy.csv") as myfile:
firstline = True
for line in myfile:
if firstline:
mykeys = ''.join(line.split()).split(',')
firstline = False
else:
values = ''.join(line.split()).split(',')
for n in range(len(mykeys)):
output_dict[mykeys[n].rstrip('"').lstrip('"')] = values[n].rstrip('"').lstrip('"')
print(output_dict)
parserd_list.append(output_dict)
#print(parserd_list)
(通常,我的csv列数超过20,但我提供了一个示例文件。)
(我使用了rstrip/lstrip来消除双引号。)
Output getting:
{'cdrRecordType': '1'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294933'}
这是print
内for
循环的输出。最终的输出也是一样的
我不知道我犯了什么错误。请有人帮我纠正一下
提前谢谢
使用csv.DictReader
代码缩进错误
这两条线:
可以简单地取消缩进,使其与上面的for循环位于同一行上。除此之外,您需要为每个新文件行设置一个新的dict
您可以这样做:
output_dict = {}
就在键的for循环之前如上所述,有一些图书馆将使生活更轻松。但是,如果您想继续附加字典,您可以加载文件的行,关闭它,并同样处理这些行:
您应该使用the ^{} module ,而不是手动解析CSV文件
这将导致更简单的脚本,并有助于优雅地处理边缘情况(例如标题行、引用不一致的字段等)
输出:
如果您打算手动解析,以下是一种方法:
输出:
相关问题 更多 >
编程相关推荐