您应该使用
the
csv
module
.
这将产生一个更简单的脚本,并有助于优雅地处理边缘情况(例如,标题行、不一致引用的字段等)。
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'}