Home > Mobile >  multiple csv files data to single json file
multiple csv files data to single json file

Time:11-23

I had two csv files named mortality1 and mortality2 and i want to insert these two csv files data into a single json file...when i am inserting these data, i am unable give the two files at the same time to json file.and this is my code

import csv
import json
import pandas as pd
from glob import glob
csvfile1 = open('C:/Users/DELL/Desktop/data/mortality1.csv', 'r')
csvfile2 = open('C:/Users/DELL/Desktop/data/mortality2.csv', 'r')
jsonfile = open('C:/Users/DELL/Desktop/data/cvstojson.json', 'w')
df = pd.read_csv(csvfile1)
df.to_json(jsonfile)

i want insert the 2 csv files data at the same time to the json file

CodePudding user response:

If both of your csv data are having similar structure, then you can append the data frames to one another, and then convert it to a JSON. Like

import csv
import json
import pandas as pd
from glob import glob
csvfile1 = open('C:/Users/DELL/Desktop/data/mortality1.csv', 'r')
csvfile2 = open('C:/Users/DELL/Desktop/data/mortality2.csv', 'r')
jsonfile = open('C:/Users/DELL/Desktop/data/cvstojson.json', 'w')

# Read and append both dataframes to single one
df = pd.read_csv(csvfile1).append(pd.read_csv(csvfile2))

# Create the json representation of all rows together.
df.to_json(jsonfile, orient="records")
  • Related