


The below example code demonstrates how to convert a CSV file to a JSON file in Python using the Dataframe.to_json() method. Since the Dataframe.to_json() method takes a DataFrame as input, we will use the pandas.readcsv() method to first read the CSV file as DataFrame. The orient argument is useful to specify how we want our JSON string to be formatted, and there are various options for both Series and DataFrame input. If no path is provided, the method returns the JSON string as output and returns nothing if the path is provided.

Call the ‘writer’ function passing the CSV file as a parameter and use the ‘writerow’ method to write the JSON file content (now converted into Python dictionary) into the CSV file. Read the lines of CSV file using csv.DictReader () function. The Dataframe.to_json(path, orient) method of the Pandas module, takes DataFrame and path as input and converts it into a JSON string, and saves it at the provided path. Add the dictionary to the Python List created in step 1. With open( 'myfile.json', 'w') as file_json:Ĭonvert CSV File to JSON File in Python Using the Dataframe.to_json() Method in Python
