Introduction to CSV and JSON Files
CSV (Comma-Separated Values) and JSON (JavaScript Object Notation) are popular file formats for storing and exchanging data. They are both human-readable and can be easily parsed using Python’s built-in libraries.
Reading and Writing CSV Files
Python provides the csv module for working with CSV files. You can read and write CSV files using the module’s reader and writer objects.
Example:
import csv
# Reading a CSV file
with open('example.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row)
# Writing to a CSV file
data = [['Name', 'Age'], ['Alice', 30], ['Bob', 25]]
with open('output.csv', 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(data)
Reading and Writing JSON Files
Python provides the json module for working with JSON files. You can read and write JSON files using the module’s load, loads, dump, and dumps functions.
Example:
import json
# Reading a JSON file
with open('example.json', 'r') as jsonfile:
data = json.load(jsonfile)
print(data)
# Writing to a JSON file
data = {'name': 'Alice', 'age': 30}
with open('output.json', 'w') as jsonfile:
json.dump(data, jsonfile)
Pandas Integration with CSV and JSON Files
Pandas provides built-in methods for reading and writing CSV and JSON files, making it easy to work with these file formats.
Example:
import pandas as pd
# Reading a CSV file
df_csv = pd.read_csv('example.csv')
# Writing to a CSV file
df_csv.to_csv('output.csv', index=False)
# Reading a JSON file
df_json = pd.read_json('example.json')
# Writing to a JSON file
df_json.to_json('output.json')
Exception Handling
When working with files, it’s important to handle exceptions that may occur, such as file not found or permission errors. You can use the 'try' and 'except' blocks to catch and handle exceptions gracefully.
Example:
try:
with open("nonexistent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("You do not have permission to read the file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Hands-on Exercises
- Read a CSV file containing user information and calculate the average age of the users.
- Convert a JSON file containing a list of products and their prices to a CSV file.
- Read a JSON file containing weather data and calculate the average temperature for each month.
Real-World Example
Working with CSV and JSON files is a common task for data analysts and developers. These file formats are widely used for storing and exchanging structured data, such as product catalogs, customer databases, and financial records.
Additional Resources
- Python documentation: https://docs.python.org/3/library/csv.html
- Python documentation: https://docs.python.org/3/library/json.html
- Pandas documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html
Review Questions
- What are the differences between CSV and JSON file formats?
- 2. How do you read and write CSV files using Python’s
'csv'module? - How do you read and write JSON files using Python’s
'json'module? - What are the benefits of using Pandas for working with CSV and JSON files?
Summary and Next Steps
In this lesson, you have learned about:
- CSV and JSON file formats and their use cases
- Reading and writing CSV files using the
'csv'module - Reading and writing JSON files using the
'json'module - Pandas integration with CSV and JSON files
In the next lesson, you will learn about web scraping with Beautiful Soup. This skill will allow you to extract data from websites to use in your Python applications.
Remember to review the material periodically and practice your skills to reinforce your learning. Good luck on your journey to becoming a Python developer!



