Welcome folks today in this blog post we will be exporting csv
file to json
and saving it as json
file inside the root directory in command line using csv
module. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 |
import csv import json csv_file = open('output.csv', 'r') csv_reader = csv.reader(csv_file) field_names = next(csv_reader) data = [] for row in csv_reader: data.append(dict(zip(field_names, row))) |
As you can see we are importing the csv
and json
module and then we are loading the input
csv file called output.csv
in read mode. And then we are reading the content of the csv
file using the reader()
method. And then we are using a simple for
loop to write all the contents
of the csv file inside a data
array. For this we are using the append()
method.
Dumping Data inside JSON File and Saving it
Now guys we will be opening the json
file using the open()
method and dump all the data present inside the data
array into it using the dumps()
method as shown below
1 2 3 4 5 6 7 |
json_data = json.dumps(data) json_file = open('file.json', 'w') json_file.write(json_data) csv_file.close() json_file.close() |
Now before running this python script you need to create the output.csv
file inside the root directory as shown below
output.csv
1 2 3 4 5 |
Name,Age,Country Alice,25,USA Bob,30,Canada Claire,35,UK David,40,Australia |
Now if you execute the python
script inside the command line you will see the file.html
will be created as shown below
python app.py