Using the CSV module to write CSV data
In this next demonstration, you will read the output data from the previous chapter and convert it to CSV format.
To start off with, I will create a file called json_to_csv.py
which will make use of both the csv
module and the json
module. In the json_to_csv.py
file, I will start by importing both the csv
module and the json
module and reading the JSON data from the scf_extract.json
file into a Python list:
import csv import json ## read in the input json data fin = open("../data/input_data/scf_extract.json","r") json_data = json.load(fin) fin.close()
Writing CSV data using the csv
module is a bit like reading data with the CSV module in reverse. When opening a file with write permission, you can use the corresponding file object to create a writer
object. This is done using the csv.writer()
function. The writerow()
function of the writer
object will take an array of values and write it to a row in the output file.
Recall that the extracted data entries...