- Learning Objectives
- Prerequisites
- Introduction
- What is a CSV File?
- What is a JSON File?
- Why are CSV and JSON Files Required?
- Working with the csv Module
- Working with the json Module
- Serialization and Deserialization
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand CSV files.
- Understand JSON files.
- Read CSV files.
- Write CSV files.
- Read JSON files.
- Write JSON files.
- Understand serialization and deserialization.
- Work with structured data.
Before learning this chapter, you should know:
- File Handling
- Lists
- Dictionaries
- Functions
- Modules
Modern applications exchange and store structured data using standard file formats.
The two most commonly used formats are:
- CSV
- JSON
Examples
- Student records
- Employee information
- Product details
- API responses
- Configuration files
- Reports
Python provides built-in modules to work with both formats.
CSV stands for Comma-Separated Values.
It stores data in rows and columns where each value is separated by a comma.
Example
ID,Name,Marks
101,Alice,92
102,Bob,85
103,Charlie,90
- Human-readable
- Lightweight
- Easy to edit
- Tabular structure
- Widely supported
JSON stands for JavaScript Object Notation.
It stores structured data using key-value pairs.
Example
{
"id":101,
"name":"Alice",
"marks":92
}- Human-readable
- Platform-independent
- Supports nested structures
- Commonly used in APIs
- Easy to exchange data
CSV is useful for
- Reports
- Excel data
- Databases
- Data analysis
JSON is useful for
- APIs
- Web applications
- Configuration files
- Data exchange
- Cloud applications
Python provides
csvmodule.
Import
import csvCommon Functions
- csv.reader()
- csv.writer()
- csv.DictReader()
- csv.DictWriter()
Example
import csv
with open("students.csv","r") as file:
reader = csv.reader(file)
for row in reader:
print(row)Example
import csv
with open("students.csv","w",newline="") as file:
writer = csv.writer(file)
writer.writerow(["ID","Name","Marks"])
writer.writerow([101,"Alice",92])Example
import csv
with open("students.csv","r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row)Example
import csv
with open("students.csv","w",newline="") as file:
fieldnames=["ID","Name","Marks"]
writer=csv.DictWriter(file,fieldnames=fieldnames)
writer.writeheader()
writer.writerow(
{"ID":101,"Name":"Alice","Marks":92}
)Python provides
jsonmodule.
Import
import jsonCommon Functions
- json.dump()
- json.dumps()
- json.load()
- json.loads()
Example
import json
student = {
"id":101,
"name":"Alice",
"marks":92
}
with open("student.json","w") as file:
json.dump(student,file,indent=4)Example
import json
with open("student.json","r") as file:
data=json.load(file)
print(data)Serialization is the process of converting a Python object into JSON format.
Example
json.dumps(dictionary)Deserialization is the process of converting JSON data back into Python objects.
Example
json.loads(json_string)| CSV | JSON |
|---|---|
| Tabular Data | Key-Value Data |
| Rows and Columns | Objects and Arrays |
| Simpler Structure | More Flexible Structure |
| Best for Spreadsheet Data | Best for APIs and Web Applications |
Python Program
↓
CSV / JSON Module
↓
Open File
↓
Read / Write Data
↓
Close File
↓
Storage Device
- Simple format.
- Lightweight.
- Easy to edit.
- Excellent for tabular data.
- Supports nested data.
- Human-readable.
- Easy data exchange.
- Widely used by APIs.
- Use
withwhile opening files. - Validate JSON before processing.
- Use
DictReaderfor meaningful CSV column access. - Use
indentwhile writing JSON for better readability. - Handle exceptions when reading files.
Forgetting
newline=""while writing CSV on some platforms, which can result in extra blank lines.
Writing invalid JSON syntax manually.
Using
json.load()instead of
json.loads()Remember
load()→ Fileloads()→ String
Confusing
dump()and
dumps()Remember
dump()→ Writes to a file.dumps()→ Returns a JSON string.
import csv
with open("students.csv","r") as file:
reader = csv.reader(file)
for row in reader:
print(row)import csv
with open("students.csv","w",newline="") as file:
writer=csv.writer(file)
writer.writerow(["ID","Name","Marks"])
writer.writerow([101,"Alice",95])import csv
with open("students.csv","r") as file:
reader=csv.DictReader(file)
for row in reader:
print(row["Name"])import csv
with open("students.csv","w",newline="") as file:
fields=["ID","Name","Marks"]
writer=csv.DictWriter(file,fieldnames=fields)
writer.writeheader()
writer.writerow(
{"ID":102,"Name":"Bob","Marks":88}
)import json
student={
"id":101,
"name":"Alice",
"marks":92
}
with open("student.json","w") as file:
json.dump(student,file,indent=4)import json
with open("student.json","r") as file:
student=json.load(file)
print(student)import json
student={
"id":101,
"name":"Alice"
}
result=json.dumps(student)
print(result)import json
text='{"name":"Alice","marks":90}'
student=json.loads(text)
print(student)import json
students=[
{"id":1,"name":"Alice"},
{"id":2,"name":"Bob"}
]
print(json.dumps(students,indent=4))import json
data={
"course":"Python",
"duration":"3 Months"
}
print(json.dumps(data,indent=4))Program Starts
↓
Import csv/json
↓
Open File
↓
Read / Write Data
↓
Convert Objects
↓
Close File
↓
Program Ends
Python Program
│
├── csv Module
│
├── json Module
│
├── CSV File
│
└── JSON File
A CSV file stores tabular data using comma-separated values.
JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging structured data.
csvjsoncsv.reader()returns each row as a list.csv.DictReader()returns each row as a dictionary using column names as keys.
json.dump()writes JSON data to a file.json.dumps()converts a Python object into a JSON string.
json.load()reads JSON from a file.json.loads()parses JSON from a string.
Serialization converts a Python object into JSON format.
Deserialization converts JSON data back into Python objects.
JSON.
- Read student records from a CSV file.
- Write employee details to a CSV file.
- Read data using
DictReader. - Write JSON data to a file.
- Read JSON from a file.
- Serialize a Python dictionary.
- Deserialize a JSON string.
- CSV → Comma-Separated Values
- JSON → JavaScript Object Notation
csv.reader()→ Read CSVcsv.writer()→ Write CSVjson.dump()→ Write JSON to filejson.dumps()→ Python object → JSON stringjson.load()→ Read JSON from filejson.loads()→ JSON string → Python object- Serialization → Python → JSON
- Deserialization → JSON → Python
In this chapter, you learned:
- CSV Files
- JSON Files
- csv Module
- json Module
- Reading CSV
- Writing CSV
- Reading JSON
- Writing JSON
- Serialization
- Deserialization
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision