Search code examples
python-3.xexport-to-csv

Python: how to replace by blank or NA as exception in a list of properties?


I tried google some hours without solution. So created this account try to ask by myself. I am using python to generate a user list and export as csv. I can print(Users['Id'],Users['Name']) without error as all users have these two fields. But if I print(Users['Id'],Users['Name'],Users['Email']), I met errors, if I write try and exception as pass, I got only one user result S3 alex as only alex has the field Email. May I know if there is a way that I can put all the 6 field names as the table header. Then whenever a user has no value on any fields, just put NA or leave it blank ? Thanks.

My code looks like this:

fo=open('Userlist.csv','w',newline='')

data_obj=csv.writer(fo)

data_obj.writerow(['cnt','Name','Id'])

cnt=1

result = get_users()

for user in result['Users']:

   print(user['Name'],user['Id']) # to see result

   data_obj.writerow([user['Name'],user['Id']])  # to write data into csv rows

   row_number += 1

fo.close()

#If I print(result), get below result with different fields:

    "Users": [
        {
            "Id": "S-1xxxx",
            "Name": "S1 Peter",
            "State": "DISABLED",
            "UserRole": "USER"
        },
        {
            "Id": "S-2xxxx",
            "Name": "S2 Mary",
            "State": "DISABLED",
            "UserRole": "USER"
        },
        {
            "Id": "S-3xxxx",
            "Email": "[email protected]",
            "Name": "S3 alex",
            "State": "ENABLED",
            "UserRole": "USER",
            "EnabledDate": "2020-1-5"
        },
        {
            "Id": "S-4xxxx",
            "Name": "S3 brand",
            "State": "DELETED",
        }]

[expected result][1]


  [1]: https://i.sstatic.net/fIMMB.png

Solution

  • with open("Userlist.csv", "w") as f:
        w = csv.writer(f)
        w.writerow(["Id", "Name", "Email"])
        for user in users:
            w.writerow([user.get("Id"), user.get("Name"), user.get("Email")])
    

    The with keyword causes python to use a context manager and means you don't need to worry about closing your file. It's not vital to this solution, but it's good practice.

    Using get() looks for your key and returns None if it doesn't exist, thus not throwing an error if it doesn't.