Table of contents
1.
Introduction 
2.
Handling CSV files in Python
2.1.
Reading CSV files in Python
2.2.
Writing on CSV files in Python
3.
Handling JSON files in Python
4.
CSV to JSON in Python
5.
JSON to CSV in Python
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Aug 11, 2025
Easy

Handling CSV/JSON files in Python

Introduction 

Handling files is essential in any language, either a standard text file or a specific format file like CSV or JSON files, so let's understand how we can use Python to handle and do read and write operations with CSV and JSON files. 

Let's first understand the format of a CSV file. 

The CSV (Comma Separated Values) file format is a simple way to save tabular data in spreadsheets and databases. A CSV file is a plain text file with tabular data (numbers and text). Each line in the file represents a data record. There are one or more fields in each entry separated by commas. Using a comma as a field separator gives this file format its name.

JSON stands for JavaScript Object Notation in its entire form. The data is stored and transferred using a script (executable) file written in a computer language. In JSON, the text is represented as a quoted string containing the value in a key-value mapping.

a ={"name":"John",
  "age":31,
    "Salary":25000}

Having understood the basics of CSV and JSON, let's see how we can handle them in Python. 

Also See, Floor Division in Python, Swapcase in Python

Handling CSV files in Python

There is an inbuilt module in Python that is used to specially handle CSV files in Python, the module is CSV, and we have to import it and use it to manipulate CSV files. 

There are two kinds of entries in a CSV file: Fields, the column's name, and Rows. 

Also See, Python Round Function and Convert String to List Python.

Reading CSV files in Python

Reading in CSV file is done through CSV.reader, which opens the file to read; the argument to this function is the '/file/path', and then we can run functions on the output of this function. 

Let's understand from code. 

The CSV file we are using is addresses.csv which can be downloaded from here

Code: 

import csv # importing the csv module.
 
# csv file path
filename = "addresses.csv"
#opening the csvfile in traditional way
csvfile=open(filename,'r')
 
# initializing the titles and rows list
fields = []
rows = []
 
# reading CSV file
# creating a CSV reader object
csvreader = csv.reader(csvfile)
#this object is our go-to for every change in the
# we will just interact with it.
# csvreader is an iterator it has the data in the form of rows
# a next is called on it, then it goes to the next row.
# so the first row will have fields, and correspondingly we can
# go for next.
 
# extracting field names through first row
fields = next(csvreader)
# next function returns the current row and
#advances the row to the next.
 
 
# extracting each data row one by one
# in for loop next is automatically called for
# an iterator.
for row in csvreader:
        rows.append(row)
 
# get total number of rows
print("Total no. of rows: %d"%(csvreader.line_num))
 
# printing the field names
print('Field names are:' + ', '.join(field for field in fields))
 
# printing first 5 rows
print('\nFirst 5 rows are:\n')
for row in rows[:5]:
    # parsing each column of a row
    for col in row:
        print(col,end=" ")
    print('\n')
You can also try this code with Online Python Compiler
Run Code

Output: 

Total no. of rows: 6
Field names are: John, Doe, 120 Jefferson st., Riverside, NJ, 08075

The First 5 rows are:

Jack McGinnis 220 hobo Av. Phila PA 09119 

John "Da Man" Repici 120 Jefferson St. Riverside NJ 08075 

Stephen Tyler 7452 Terrace "At the Plaza" road SomeTown SD 91234 

 Blankman SomeTown SD 00298 

Joan "the bone", Anne Jet 9th, at Terrace plc Desert City CO 00123 

The main things to note in this program are already mentioned in the comments, but still focusing on csvreader, which has been returned by CSV.reader(filename) as an iterator to the file. It stores values of the rows, the next function returns the current row and moves the iterator to the next row, and this is how we can iterate through the whole CSV file. 

You can practice by yourself with the help of online python compiler.

Writing on CSV files in Python

import CSV
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
 
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
         ['Sanchit', 'COE', '2', '9.1'],
         ['Aditya', 'IT', '2', '9.3'],
         ['Sagar', 'SE', '1', '9.5'],
         ['Prateek', 'MCE', '3', '7.8'],
         ['Sahil', 'EP', '2', '9.1']]
 
# name of csv file
filename = "student_records.csv"
 
# writing to csv file
with open(filename, 'w') as csvfile:
    # creating a csv writer object
    csvwriter = csv.writer(csvfile)
     
    # writing the fields
    csvwriter.writerow(fields)
     
    # writing the data rows
    csvwriter.writerows(rows)
You can also try this code with Online Python Compiler
Run Code

This is a simple example to write the data to a CSV file; there are a lot more utilities to write the data in CSV; if you have a dictionary of data to be written to CSV, we can use another function CSV.dictwriter(filename), which will take an array of dictionaries and automatically make CSV out of them. 

import CSV
# my data rows as dictionary objects
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
         {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
         {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
         {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
         {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
         {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]
 
# field names
fields = ['name', 'branch', 'year', 'cgpa']
 
# name of csv file
filename = "university_records.csv"
 
# writing to csv file
with open(filename, 'w') as csvfile:
    # creating a csv dict writer object
    writer = csv.DictWriter(csvfile, fieldnames = fields)
     
    # writing headers (field names)
    writer.writeheader()
     
    # writing data rows
    writer.writerows(mydict)
You can also try this code with Online Python Compiler
Run Code

Like these, many more functions can be used, but mostly above-explained functions are enough in most use cases. For more functionalities, have a look at this page: 

Official Python Documentation

Handling JSON files in Python

Now let's see how we can handle JSON files; for this, too, we have a JSON module that can handle all things related to file handing in JSON. 

If we closely look at the JSON format, it just looks like a list of dictionaries. The difference is in JSON; it's a string of text, so we need to convert our python objects to text before writing to a file and those functionalities are offered by json library. 

JSON not only supports dictionaries but also various otter primitive data types like list, tuples, str, int, long, float and boolean values.

The process of encoding a JSON is called Serialisation; this process transforms data into bytes and is necessary to change our data to JSON, which is a standard format to send data over a network, as this is a basic requirement in Rest APIs, Python's dump() function is used for Serialisation of data and then it can be written to a file easily. 

Let's understand from an Example.

import JSON
 
data = {
      "Subjects": {
                  "Maths":85,
                  "Physics":90
                   }
      }
 
jsonFile=open("example.json",'w')
json.dump(data, jsonFile)
You can also try this code with Online Python Compiler
Run Code

This code should make a JSON file of the name 'example.json' and write the data to it, 

The data written is serialised from the variable data and then dumped to the file that we have opened up. 

Now Deserialisation is the opposite of Serialisation. In this, a JSON is read and converted into python objects. 

The dump method serialises the data, whereas the load method deserialises the data. 

Let's have an example: 

import JSON
 
file =open('file.json','r')
data = json.load(file)
You can also try this code with Online Python Compiler
Run Code

This will load up the JSON values in data; this is deserialisation. 

For more information and functions, visit the official documentation of the JSON module

CSV to JSON in Python

Now let's look at how to convert CSV to JSON.

Image Source

This picture sums it all up, 

The following algorithm is needed to be followed: 

  1. Create a python list. 
  2. Convert each line of CSV into a dictionary using CSV.DictReader() and append it to the list. 
  3. Serialise the data with dump() and write it to the JSON file. 

Example: 

Input:  data.csv

a,b,c
25,84,com
41,52,org
58,79,io,
93,21,co

Code: 

import csv
import json

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []
     
    #read csv file
    with open(csvFilePath, encoding='utf-8') as csvf:
        #load csv file data using csv library's dictionary reader
        csvReader = csv.DictReader(csvf)

        #convert each csv row into python dict
        for row in csvReader:
            #add this python dict to json array
            jsonArray.append(row)
 
    #convert python jsonArray to JSON String and write to file
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)
         
csvFilePath = r'data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)
You can also try this code with Online Python Compiler
Run Code

Output: 

data.json
[
    {
        "a": "25",
        "b": "84",
        "c": "com"
    },
    {
        "a": "41",
        "b": "52",
        "c": "org"
    },
    {
        "a": "58",
        "b": "79",
        "c": "io"
    },
    {
        "a": "93",
        "b": "21",
        "c": "co"
    }
]

JSON to CSV in Python

Similarly, a JSON file can also be converted to CSV, and simply, we just need to read the JSON and then make CSV out of it directly using the csvwriter function. 

import json
import csv
with open('input.json') as json_file:
    jsondata = json.load(json_file)
data_file = open('output.csv', 'w', newline='')
csv_writer = csv.writer(data_file)
count = 0
for data in jsondata:
    if count == 0:
        header = data.keys()
        csv_writer.writerow(header)
        count += 1
    csv_writer.writerow(data.values())
data_file.close()
You can also try this code with Online Python Compiler
Run Code

 

Check out Escape Sequence in Python

Frequently Asked Questions

1. What is the application of JSON files?
It's mostly used in-network calls; all the Rest API calls mostly use JSON, the preferred mode of sending data. 
2. What is the application of CSV files? 
CSV files are mostly used in showing the output or a simplified version of an excel sheet or a database. 
3. What are the advantages of JSON?
JSON is self-describing. The syntax and hierarchical structure of the JSON strings can, in some cases, be interpreted by applications that do not already know what data to expect.
JSON is simple text.
JSON  is compact.
JSON is easy to learn, easy to read and understand.
4. What are various python modules to handle JSON and CSV?
JSON and CSV modules are the modules generally used to handle them. 

Conclusion

So, in a nutshell, we just need to understand the functionalities of JSON and CSV modules in Python, and most of our needs will be satisfied. 

Recommended Reading:

 

Live masterclass