[英]Using csv.DictWriter to write data to CSV
我有一個python字典對象,我需要將數據寫入CSV文件。 我是python編程的新手。 所以我想知道是否有人可以指導我。
這是我的對象。
dict = [{u'interface': [{u'interface-down-reason': u'LACP Convergence Timeout',
u'interface-name': u'ethernet28:1',
u'leaf-group': u'R2',
u'member-type': u'',
u'mode': u'lacp',
u'op-state': u'down',
u'phy-state': u'up',
u'switch-name': u'R2L2'},
{u'interface-down-reason': u'LACP Protocol Initiated',
u'interface-name': u'ethernet28:1',
u'leaf-group': u'R2',
u'member-type': u'',
u'mode': u'lacp',
u'op-state': u'down',
u'phy-state': u'up',
u'switch-name': u'R2L1'}],
u'name': u'LACP-Test'},
{u'interface': [{u'interface-down-reason': u'None',
u'interface-name': u'ethernet54:4',
u'leaf-group': u'R1',
u'member-type': u'',
u'mode': u'static-auto-vswitch-inband',
u'op-state': u'up',
u'phy-state': u'up',
u'switch-name': u'R1L1'},
{u'interface-down-reason': u'None',
u'interface-name': u'ethernet54:4',
u'leaf-group': u'R1',
u'member-type': u'',
u'mode': u'static-auto-vswitch-inband',
u'op-state': u'up',
u'phy-state': u'up',
u'switch-name': u'R1L2'}],
u'name': u'LAX-K8-MASTER-NODE'}]
如您所見,它由多個鍵值對組成,某些鍵具有字典列表。
我一直在閱讀csv.Dictwiter,我想包含如下所示的字段名稱
export_fields = ['name','interface-name', 'op-state', 'phy-state']
但是,挑戰在於某些字段名稱在鍵“接口”的字典中。
因此,我如何隔離它,以便可以將其寫入CSV文件。
如果有人可以分享邏輯或指導我,我可以從那里接受。
感謝您的回應。
您不能在不添加某種轉換層的情況下使用嵌套結構來編寫2D表數據-Python不知道在哪里尋找元素,也不知道嵌套如何影響它們。 因此,提供的數據結構如下:
data = [{u'interface': [{u'interface-down-reason': u'LACP Convergence Timeout',
u'interface-name': u'ethernet28:1',
u'leaf-group': u'R2',
u'member-type': u'',
u'mode': u'lacp',
u'op-state': u'down',
u'phy-state': u'up',
u'switch-name': u'R2L2'},
{u'interface-down-reason': u'LACP Protocol Initiated',
u'interface-name': u'ethernet28:1',
u'leaf-group': u'R2',
u'member-type': u'',
u'mode': u'lacp',
u'op-state': u'down',
u'phy-state': u'up',
u'switch-name': u'R2L1'}],
u'name': u'LACP-Test'},
{u'interface': [{u'interface-down-reason': u'None',
u'interface-name': u'ethernet54:4',
u'leaf-group': u'R1',
u'member-type': u'',
u'mode': u'static-auto-vswitch-inband',
u'op-state': u'up',
u'phy-state': u'up',
u'switch-name': u'R1L1'},
{u'interface-down-reason': u'None',
u'interface-name': u'ethernet54:4',
u'leaf-group': u'R1',
u'member-type': u'',
u'mode': u'static-auto-vswitch-inband',
u'op-state': u'up',
u'phy-state': u'up',
u'switch-name': u'R1L2'}],
u'name': u'LAX-K8-MASTER-NODE'}]
您必須手動指示它寫什么,在您的情況下這很簡單:
# on Python 3.x use: open("output.csv", "wt", endline="")
with open("output.csv", "wb") as f: # open output.csv for writing
writer = csv.writer(f) # create a CSV writer
writer.writerow(['name', 'interface-name', 'op-state', 'phy-state']) # write the header
for endpoint in data: # loop through your data
name = endpoint["name"]
for it in endpoint["interface"]: # loop through all interfaces
writer.writerow([name, it["interface-name"], it["op-state"], it["phy-state"]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.