Modern applications constantly exchange and store structured data. Two of the most widely used file formats for this purpose are CSV (Comma-Separated Values) and JSON (JavaScript Object Notation). Python provides built-in modules that make it easy to read, write, and process these files.
CSV files are commonly used to store tabular data such as student records, sales reports, and datasets. JSON files are widely used for APIs, configuration files, web applications, and data exchange because they can represent complex hierarchical data.
Whether you are working in data analytics, web development, automation, or machine learning, understanding CSV and JSON files is an essential Python skill.
In this lesson, you will learn what CSV and JSON files are, why they are important, compare their features, import Python’s built-in modules, and explore their real-world applications.
After completing this lesson, you will be able to:
csv and json modules.CSV (Comma-Separated Values) is a simple text file format used to store tabular data. Each row represents one record, and commas separate individual values.
Example of a CSV file:
Name,Course,Marks
Rahul,Python,92
Priya,Data Analytics,95
Amit,SQL,88
CSV files are widely supported by spreadsheet software such as Microsoft Excel, Google Sheets, and many database systems.
JSON (JavaScript Object Notation) is a lightweight data-interchange format used to represent structured information as key-value pairs.
Example of a JSON file:
{
"name": "Rahul",
"course": "Python",
"marks": 92
}
JSON is widely used in web applications, REST APIs, cloud services, mobile applications, and configuration files.
CSV and JSON files allow different applications and systems to exchange data efficiently.
For example:
| Feature | CSV | JSON |
|---|---|---|
| Data Format | Rows and Columns | Key-Value Pairs |
| Supports Nested Data | No | Yes |
| Human Readable | Yes | Yes |
| Common Usage | Datasets, Reports | APIs, Web Applications |
| Best For | Tabular Data | Structured Data |
| File Extension | .csv | .json |
Python provides the built-in csv module for working with CSV files.
import csv
No installation is required because the module is included with Python.
Python provides the built-in json module for working with JSON data.
import json
The json module is also part of Python’s standard library.
| Application | CSV | JSON |
|---|---|---|
| Student Records | ✔ | ✔ |
| Sales Reports | ✔ | |
| REST APIs | ✔ | |
| Machine Learning Datasets | ✔ | |
| Configuration Files | ✔ | |
| Web Applications | ✔ |
import csv
import json
print("CSV Module Imported Successfully")
print("JSON Module Imported Successfully")
Output
CSV Module Imported Successfully
JSON Module Imported Successfully
Consider the following program.
import csv
import json
print("Modules Loaded")
Execution Steps
csv module.json module.Output
Modules Loaded
.xlsx) files.csv or json modules using pip, even though they are built into Python.In this section, you learned what CSV and JSON files are, their characteristics, differences, and real-world applications. You also learned how to import Python’s built-in csv and json modules and understand when each file format should be used. In the next section, you will learn how to read and write CSV files using csv.reader() and csv.writer(), write multiple rows, work with different delimiters, and apply CSV processing in practical Python programs.
In the previous section, you learned what CSV files are, why they are important, and how Python provides the built-in csv module for working with them. CSV files are one of the most common formats used in data analytics, reporting systems, and spreadsheet applications because they store tabular data in a simple, readable format.
In this section, you will learn how to read CSV files using csv.reader(), write data using csv.writer(), write multiple rows, work with different delimiters, and apply these techniques in practical Python programs.
Python uses the csv.reader() function to read data from CSV files.
students.csv contains:Name,Course,Marks
Rahul,Python,92
Priya,Data Analytics,95
Amit,SQL,88
import csv
file = open("students.csv", "r")
reader = csv.reader(file)
for row in reader:
print(row)
file.close()
Output
['Name', 'Course', 'Marks']
['Rahul', 'Python', '92']
['Priya', 'Data Analytics', '95']
['Amit', 'SQL', '88']
Each row is returned as a list.
Most CSV files contain a header. You can skip it using the next() function.
import csv
file = open("students.csv", "r")
reader = csv.reader(file)
next(reader)
for row in reader:
print(row)
file.close()
Output
['Rahul', 'Python', '92']
['Priya', 'Data Analytics', '95']
['Amit', 'SQL', '88']
The csv.writer() function writes data into CSV files.
import csv
file = open("employees.csv", "w", newline="")
writer = csv.writer(file)
writer.writerow(["Name", "Department", "Salary"])
writer.writerow(["Neha", "HR", 50000])
file.close()
Contents of employees.csv
Name,Department,Salary
Neha,HR,50000
The writerows() method writes multiple records at once.
import csv
rows = [
["Name", "Course", "Marks"],
["Rahul", "Python", 92],
["Priya", "Data Analytics", 95],
["Amit", "SQL", 88]
]
file = open("students.csv", "w", newline="")
writer = csv.writer(file)
writer.writerows(rows)
file.close()
Contents of students.csv
Name,Course,Marks
Rahul,Python,92
Priya,Data Analytics,95
Amit,SQL,88
newline="" ParameterWhen writing CSV files, it is recommended to use newline="". This prevents extra blank lines from appearing in the output file, especially on Windows systems.
file = open("students.csv", "w", newline="")
Although commas are the default separator, CSV files can also use other delimiters such as semicolons or tabs.
import csv
file = open("students.csv", "w", newline="")
writer = csv.writer(file, delimiter=";")
writer.writerow(["Name", "Marks"])
writer.writerow(["Rahul", 92])
file.close()
Contents of students.csv
Name;Marks
Rahul;92
import csv
rows = [
["Roll No", "Name", "Course"],
[101, "Rahul", "Python"],
[102, "Priya", "SQL"]
]
file = open("student_database.csv", "w", newline="")
writer = csv.writer(file)
writer.writerows(rows)
file.close()
print("Student Database Created")
Output
Student Database Created
import csv
file = open("sales.csv", "w", newline="")
writer = csv.writer(file)
writer.writerow(["Product", "Quantity", "Amount"])
writer.writerow(["Laptop", 5, 275000])
writer.writerow(["Mouse", 20, 16000])
file.close()
Contents of sales.csv
Product,Quantity,Amount
Laptop,5,275000
Mouse,20,16000
csv module before working with CSV files.newline="" while writing CSV files.next() to skip header rows when needed.writerows() when writing multiple records.Consider the following program.
import csv
file = open("students.csv", "r")
reader = csv.reader(file)
for row in reader:
print(row)
file.close()
Execution Steps
csv module.csv.reader() creates a reader object.for loop reads one row at a time.Output
['Name', 'Course', 'Marks']
['Rahul', 'Python', '92']
['Priya', 'Data Analytics', '95']
['Amit', 'SQL', '88']
csv module.newline="" when writing CSV files.writerow() with writerows().In this section, you learned how to read CSV files using csv.reader(), write records using csv.writer(), create multiple records using writerows(), skip header rows, and work with custom delimiters. You also explored practical examples, best practices, execution flow, and common beginner mistakes. In the next section, you will learn how to work with JSON files using the json module, including json.load(), json.dump(), converting Python dictionaries to JSON, pretty-printing JSON data, and handling structured data efficiently.
In the previous section, you learned how to read and write CSV files using Python’s csv module. While CSV files are ideal for storing tabular data, many modern applications require a more flexible format that supports nested structures and key-value pairs. This is where JSON (JavaScript Object Notation) becomes extremely useful.
JSON is one of the most widely used data formats in web development, REST APIs, cloud applications, mobile apps, and configuration files. Python provides the built-in json module to easily read, write, and manipulate JSON data.
In this section, you will learn how to read JSON files, write JSON files, convert Python dictionaries to JSON, format JSON output, and explore practical real-world applications.
Python reads JSON files using the json.load() function.
student.json contains:{
"name": "Rahul",
"course": "Python",
"marks": 92
}
import json
file = open("student.json", "r")
student = json.load(file)
print(student)
file.close()
Output
{'name': 'Rahul', 'course': 'Python', 'marks': 92}
The JSON data is converted into a Python dictionary.
After loading a JSON file, you can access values using dictionary keys.
import json
file = open("student.json", "r")
student = json.load(file)
print(student["name"])
print(student["marks"])
file.close()
Output
Rahul
92
The json.dump() function writes Python objects into a JSON file.
import json
student = {
"name": "Priya",
"course": "Data Analytics",
"marks": 95
}
file = open("student.json", "w")
json.dump(student, file)
file.close()
Contents of student.json
{"name": "Priya", "course": "Data Analytics", "marks": 95}
For better readability, use the indent parameter.
import json
student = {
"name": "Priya",
"course": "Data Analytics",
"marks": 95
}
file = open("student.json", "w")
json.dump(student, file, indent=4)
file.close()
Contents of student.json
{
"name": "Priya",
"course": "Data Analytics",
"marks": 95
}
The json.dumps() function converts a Python object into a JSON-formatted string.
import json
student = {
"name": "Rahul",
"marks": 92
}
json_data = json.dumps(student)
print(json_data)
Output
{"name": "Rahul", "marks": 92}
Notice that dumps() returns a string instead of writing to a file.
The json.loads() function converts a JSON string into a Python dictionary.
import json
json_text = '{"name":"Rahul","marks":92}'
student = json.loads(json_text)
print(student)
Output
{'name': 'Rahul', 'marks': 92}
import json
employee = {
"id": 101,
"name": "Neha",
"department": "HR"
}
file = open("employee.json", "w")
json.dump(employee, file, indent=4)
file.close()
print("Employee Record Saved")
Output
Employee Record Saved
Suppose config.json contains:
{
"theme": "dark",
"language": "English"
}
import json
file = open("config.json", "r")
config = json.load(file)
print(config["theme"])
file.close()
Output
dark
json.load() for reading JSON files.json.dump() for writing JSON files.indent=4 for readable JSON output.| Application | Purpose |
|---|---|
| REST APIs | Exchange data between client and server. |
| Web Applications | Store configuration settings. |
| Mobile Apps | Transfer structured information. |
| Cloud Services | Store application configurations. |
| Machine Learning | Save model settings. |
| Data Analytics | Store hierarchical datasets. |
Consider the following program.
import json
file = open("student.json", "r")
student = json.load(file)
print(student["name"])
file.close()
Execution Steps
json module.json.load() converts JSON into a Python dictionary.name key is accessed.Output
Rahul
json.load() with json.loads().json.dump() with json.dumps().json module.In this section, you learned how to read JSON files using json.load(), write JSON files using json.dump(), convert Python dictionaries to JSON strings with json.dumps(), and convert JSON strings back into Python objects using json.loads(). You also explored pretty-printing JSON, practical examples, performance tips, execution flow, and common beginner mistakes. In the final section, you will review the complete lesson through a lesson summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on File Paths, Directories, and OS Module.
In this lesson, you learned how to work with two of the most commonly used file formats in Python: CSV (Comma-Separated Values) and JSON (JavaScript Object Notation). These formats are widely used for storing, exchanging, and processing structured data in modern software applications.
You began by understanding what CSV and JSON files are, their characteristics, and the differences between them. You learned that CSV files are ideal for storing tabular data such as spreadsheets and datasets, while JSON files are better suited for structured and hierarchical data used in APIs and web applications.
Next, you explored Python’s built-in csv module to read and write CSV files using csv.reader(), csv.writer(), writerow(), and writerows(). You also learned how to skip header rows and use different delimiters.
Finally, you learned how to work with JSON files using Python’s json module. You used json.load() and json.dump() to read and write JSON files, explored json.loads() and json.dumps() for string conversion, and learned how to create readable JSON using the indent parameter.
These skills are essential for data analytics, machine learning, web development, automation, cloud computing, and software engineering, where exchanging structured data is a common requirement.
csv module to read and write CSV files.csv.reader() to read CSV records.csv.writer(), writerow(), and writerows() to create CSV files.json module to process JSON data.json.load() reads JSON files into Python objects.json.dump() writes Python objects to JSON files.json.loads() and json.dumps() work with JSON strings.indent=4 to create readable JSON files.CSV stands for Comma-Separated Values.
JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging structured data.
The built-in csv module.
The built-in json module.
csv.reader() return?It returns each row of a CSV file as a list.
writerow() and writerows()?writerow() writes a single row, while writerows() writes multiple rows.
json.load() do?It reads a JSON file and converts it into a Python object.
json.dump() do?It writes a Python object into a JSON file.
indent=4 be used?It formats JSON data to make it easier for humans to read.
Use JSON when working with nested, hierarchical, or API-based data structures.
writerows().;) delimiter.json.dumps().json.loads().indent=4.csv module.writerow() and writerows()?newline="" recommended while writing CSV files?json.load() and json.loads().json.dump() and json.dumps().Create a Python application that stores and retrieves student information using both CSV and JSON files.
Your program should:
try and except.========== STUDENT DATA MANAGER ==========
1. Add Student
2. View CSV Records
3. View JSON Records
4. Exit
Enter Student ID : 101
Enter Name : Rahul
Enter Course : Python
Enter Marks : 92
Record Saved Successfully
------------------------------------------
CSV Records
101,Rahul,Python,92
------------------------------------------
JSON Records
{
"id": 101,
"name": "Rahul",
"course": "Python",
"marks": 92
}
==========================================
Congratulations! You have learned how to work with CSV and JSON files in Python. You now understand how to read and write structured data using Python’s built-in csv and json modules, making you ready to handle real-world datasets and API responses.
In the next lesson, you will learn File Paths, Directories, and the OS Module: Complete Guide for Beginners. You will explore how to work with folders, navigate directories, create and delete directories, manage file paths, and use Python’s powerful os and os.path modules for file system operations.