Skip to content Skip to sidebar Skip to footer

Saving Python Dictionary (or Json?) As Csv

I have been trying to save the output from Google Search Console API as a CSV File. Initially, I was using sys.stdout to save what was print from the sample code they had provided.

Solution 1:

It may just be the encoding of the output file that's the problem.

It looks like the rows you get from the response are a series of dict-like objects, so this should work:

import csv
withopen("out.csv", "w", encoding="utf8") as f:
    writer = csv.writer(f)
    headers = ["Keys", "Clicks", "Impressions", "CTR", "Position"]
    writer.writerow(headers)
    forrowinrows:
        writer.writerow(
            [
                ", ".join(row.get("keys", [])),
                row["clicks"],
                row["impressions"],
                row["ctr"],
                row["postition"],
            ]
        )

The writer object accepts a number of arguments to control line separators and quoting in the output csv. Check the module docs for details.

Post a Comment for "Saving Python Dictionary (or Json?) As Csv"