3 回答

TA贡献1828条经验 获得超4个赞
使用 csv。DictReader
import csv with open("files\\CUCMdummy.csv", mode='r',newline='\n') as myFile: reader = list(csv.DictReader(myFile, delimiter=',',quotechar='"'))

TA贡献2065条经验 获得超14个赞
不应手动解析 CSV 文件,而应使用 csv 模块。
这将产生更简单的脚本,并有助于优雅地处理边缘情况(例如标题行,不一致的引号字段等)。
import csv
with open('example.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
输出:
$ python3 parse-csv.py
OrderedDict([('cdrRecordType', '1'), ('globalCallID_callManagerId', '3'), ('globalCallID_callId', '9294899')])
OrderedDict([('cdrRecordType', '1'), ('globalCallID_callManagerId', '3'), ('globalCallID_callId', '9294933')])
如果您打算手动解析,可以使用以下方法:
parsed_list = []
with open('example.csv') as myfile:
firstline = True
for line in myfile:
# Strip leading/trailing whitespace and split into a list of values.
values = line.strip().split(',')
# Remove surrounding double quotes from each value, if they exist.
values = [v.strip('"') for v in values]
# Use the first line as keys.
if firstline:
keys = values
firstline = False
# Skip to the next iteration of the for loop.
continue
parsed_list.append(dict(zip(keys, values)))
for p in parsed_list:
print(p)
输出:
$ python3 manual-parse-csv.py
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294933'}

TA贡献1878条经验 获得超4个赞
代码的缩进是错误的。
这两行:
print(output_dict)
parserd_list.append(output_dict)
可以简单地取消缩进,与它们上方的 for 循环位于同一行上。最重要的是,您需要为每个新文件行设置一个新字典。
您可以这样做:就在密钥的 for 循环之前。output_dict = {}
如上所述,有一些库将使生活更轻松。但是,如果您想坚持追加字典,则可以加载文件的行,将其关闭,然后按如下方式处理行:
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'}]
添加回答
举报