Learn how to read and write CSV and JSON files in Python using the csv and json modules. Includes syntax, examples, and differences between CSV and JSON data formats.

Reading and Writing CSV and JSON Files in Python:

Python provides powerful built-in modules to handle different types of data files easily.
Two of the most commonly used formats are CSV (Comma Separated Values) and JSON (JavaScript Object Notation).
Both formats are lightweight and widely used for storing and exchanging data.

  1. CSV Files (Comma Separated Values)

Introduction

A CSV file stores data in a tabular format (rows and columns), where each value in a row is separated by a comma (,).
They are widely used in data analysis, Excel sheets, and databases.

Reading a CSV File

import csv

with open(‘students.csv’, ‘r’) as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

Definition:

  • open(‘students.csv’, ‘r’) → Opens the file in read mode.
  • csv.reader(file) → Reads the data row by row.
  • for row in reader: → Prints each row as a list.

Writing a CSV File

import csv

with open(‘students.csv’, ‘w’, newline=”) as file:

    writer = csv.writer(file)

    writer.writerow([‘Name’, ‘Age’, ‘City’])

    writer.writerow([‘Rahul’, 21, ‘Pune’])

    writer.writerow([‘Sneha’, 22, ‘Mumbai’])

Definition:

  • csv.writer(file) → Creates a CSV writer object.
  • writer.writerow() → Writes a single row of data into the file.

Reading and Writing CSV as a Dictionary

import csv

# Writing as Dictionary

with open(‘students.csv’, ‘w’, newline=”) as file:

    fieldnames = [‘Name’, ‘Age’, ‘City’]

    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()

    writer.writerow({‘Name’: ‘Rahul’, ‘Age’: 21, ‘City’: ‘Pune’})

    writer.writerow({‘Name’: ‘Sneha’, ‘Age’: 22, ‘City’: ‘Mumbai’})

# Reading as Dictionary

with open(‘students.csv’, ‘r’) as file:

    reader = csv.DictReader(file)

    for row in reader:

        print(row[‘Name’], row[‘City’])

Output:

Rahul Pune

Sneha Mumbai

  1. JSON Files (JavaScript Object Notation)

Introduction

JSON (JavaScript Object Notation) is a lightweight format for storing and transferring data.
It uses key–value pairs, similar to Python dictionaries.

JSON is widely used in web development, APIs, and configuration files.

Reading a JSON File

import json

# Reading data from a JSON file

with open(‘student.json’, ‘r’) as file:

    data = json.load(file)

    print(data)

    print(data[‘name’])

Definition:

  • json.load(file) → Converts a JSON file into a Python dictionary.

Writing a JSON File

import json

student = {

    “name”: “Rahul”,

    “age”: 21,

    “city”: “Pune”

}

# Write data to JSON file

with open(‘student.json’, ‘w’) as file:

    json.dump(student, file, indent=4)

Definition:

  • json.dump(object, file) → Saves a Python dictionary into a JSON file.
  • indent=4 → Formats JSON data in a readable, indented structure.

Convert Between String and JSON

import json

# Convert Python dictionary to JSON string

data = {“name”: “Sneha”, “age”: 22}

json_str = json.dumps(data)

print(json_str)

# Convert JSON string back to dictionary

dict_data = json.loads(json_str)

print(dict_data)

Output:

{“name”: “Sneha”, “age”: 22}

{‘name’: ‘Sneha’, ‘age’: 22}

Key Differences: CSV vs JSON

Attribute CSV JSON
Data Structure Table (Rows & Columns) Key–Value Pair (Hierarchical)
Usage Excel, Databases, Data Storage APIs, Web Apps, Config Files
Python Module csv json
Data Format Text, comma-separated Structured, nested data

Conclusion

Both CSV and JSON formats are essential for handling and exchanging data in Python:

  • Use CSV for tabular data (like spreadsheets).
  • Use JSON for structured or web-based data (like API responses).

Python’s built-in csv and json modules make it simple to read, write, and convert data efficiently.

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

https://defineinfoloop.blogspot.com/?m=1

Leave a Reply

Your email address will not be published. Required fields are marked *