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
循环的输出。和最终输出也一样。
我不知道我在做什么错。有人请帮助纠正它。
提前致谢。
您的代码缩进是错误的。
这两行:
print(output_dict)
parserd_list.append(output_dict)
可以简单地使其与上面的for循环位于同一行。最重要的是,您需要为每个新文件行设置一个新字典。
您可以执行以下操作:output_dict = {}
在键的for循环之前。
如上所述,有些库可以使生活更轻松。但是,如果您要坚持追加字典,则可以加载文件的行,将其关闭并按如下方式处理这些行:
with open("scratch.txt") as myfile:
data = myfile.readlines()
keys = data[0].replace('"','').strip().split(',')
output_dicts = []
for line in data[1:]:
values = line.strip().split(',')
output_dicts.append(dict(zip(keys, values)))
print output_dicts
[{'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899', 'cdrRecordType': '1'}, {'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294933', 'cdrRecordType': '1'}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句