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'}]
添加回答
舉報