簡體   English   中英

Python 在寫入 CSV 文件之前檢查列數據是否存在

[英]Python before writing to CSV file check if column data is present

嗨有字典數據,如圖所示:

{'Count': 5, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-22'}, 'name': 'Default Astn'}
{'Count': 2, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-18'}, 'name': 'Default Astn'}
{'Count': 1, '_id': {'ele_id': ['ccdf-4e0b-a87c-4e7738a0ed33'], 'day': '2015-09-14'}, 'name': 'sharepoint Astn'}
{'Count': 1, '_id': {'ele_id': ['2b9f-436b-a2ff-c4bc4059a9c8'], 'day': '2015-09-14'}, 'name': 'JPL Astn'}
{'Count': 2, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-14'}, 'name': 'Default Astn'}

想要使用如下列和數據寫入 CSV:

Date        Name           Count
2015-09-22  Default Astn     5
2015-09-18  Default Astn     2
2015-09-14  sharepoint Astn  1
            JPL Astn         1
            Default Astn     2

我面臨的問題是 3 行,如果第一列已經相同,只需添加第二列和第三列。 我的代碼如下

with open('test.csv', 'wb') as f:
    fieldnames = ['Date','Name','Count']
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        for line in data:
            writer.writerow({'Date' : line['_id']['day'],'Name' : line['name'], 'Count':line['Count']})

試試這個..... 沒有測試過,但我認為邏輯保持不變......

with open('test.csv', 'wb') as f:
fieldnames = ['Date','Name','Count']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    prev_date = ''
    for line in data:
        curr_date = line['_id']['day']
        if curr_date == prev_date:
            writer.writerow({'Date' : '','Name' : line['name'], 'Count':line['Count']})
        else:
            writer.writerow({'Date' : curr_date,'Name' : line['name'], 'Count':line['Count']})
            prev_date = curr_date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM