首页 > 解决方案 > 无法使用熊猫写入 csv

问题描述

在此处输入图像描述

resource.json
[
  {
    "changedTime": "2021-03-24T18:19:57.158299+00:00",
    "createdTime": "2021-03-24T18:09:56.900636+00:00",
    "id": "/subscriptions/fd7d53ef-e290-4ab1-937e-fec061c00132/resourceGroups/ARO-SANDBOX-GBV6J-RG/providers/Microsoft.Compute/disks/aro-sandbox-gbv6j-bootstrap_OSDisk",
    "identity": null,
    "kind": null,
    "location": "eastus",
    "managedBy": "/subscriptions/fd7d53ef-e290-4ab1-937e-fec061c00132/resourceGroups/aro-sandbox-gbv6j-rg/providers/Microsoft.Compute/virtualMachines/aro-sandbox-gbv6j-bootstrap",
    "name": "aro-sandbox-gbv6j-bootstrap_OSDisk",
    "plan": null,
    "properties": null,
    "provisioningState": "Succeeded",
    "resourceGroup": "ARO-SANDBOX-GBV6J-RG",
    "sku": {
      "capacity": null,
      "family": null,
      "model": null,
      "name": "Premium_LRS",
      "size": null,
      "tier": "Premium"
    },
users.json
[
  {
    "accountEnabled": true,
    "ageGroup": null,
    "assignedLicenses": [],
    "assignedPlans": [],
    "city": null,
    "companyName": null,
    "consentProvidedForMinor": null,
    "country": null,
    "createdDateTime": "2021-03-25T18:40:48Z",
    "creationType": "Invitation",
    "deletionTimestamp": null,
    "department": null,
    "dirSyncEnabled": null,
    "displayName": "xxx2015",
    "employeeId": null,
    "facsimileTelephoneNumber": null,
    "givenName": null,
    "immutableId": null,
    "isCompromised": null,
    "jobTitle": null,
    "lastDirSyncTime": null,
    "legalAgeGroupClassification": null,
    "mail": "xxx@gmail.com",
    "mailNickname": "xxxgmail.com#EXT#",
    "mobile": null,
    "objectId": "288d8043-73c0-49e4-9360-4e38f0759bae",
    "objectType": "User",
    "odata.type": "Microsoft.DirectoryServices.User",
    "onPremisesDistinguishedName": null,
    "onPremisesSecurityIdentifier": null,
    "otherMails": [
      "xxx@gmail.com"
    ],
    "passwordPolicies": null,
    "passwordProfile": null,
    "physicalDeliveryOfficeName": null,
    "postalCode": null,
    "preferredLanguage": null,
    "provisionedPlans": [],
    "provisioningErrors": [],
    "proxyAddresses": [
      "SMTP:xxx@gmail.com"
    ],
    "refreshTokensValidFromDateTime": "2021-03-25T18:40:48Z",
    "showInAddressList": false,
    "signInNames": [],
    "sipProxyAddress": null,
    "state": null,
    "streetAddress": null,
    "surname": null,
    "telephoneNumber": null,

我正在读取两个json文件以写入 csv。数据长度不等。当第二个函数运行时,它会尝试添加headers第一列中数据的结束位置并最终给出错误Cannot insert Access, field already exists。这样做的正确方法是什么?

import json
import csv
import pandas as pd
def get_obj():
    header_added = False
    with open('C:\\users.json') as f:
        datas = json.load(f)
        for item in datas:
            for k, v in item.items():
                if k == 'objectId':
                    obj = v
                    dict1 = {'Object ID': obj }
                    with open('Azure.csv', 'a+', encoding='utf-8-sig') as f:
                        w = csv.DictWriter(f, dict1.keys())
                        if not header_added:
                           w.writeheader()
                           header_added = True
                        w.writerow(dict1))

def get_resource():
    with open('C:\\resource.json') as g:
        data1 = json.load(g)
        for item1 in data1:
            for k, v in item1.items():
                if k == 'id':
                    u_id = v
                    df1 = pd.read_csv('Azure.csv')
                    df1.insert(1, column='Access', value=u_id)
                    df1.to_csv('Azure.csv', index=False)

标签: pythonpandascsv

解决方案


推荐阅读