Opens in a new tab
Lesson 4

Working with CSV and JSON Files

Python Mastery Program, Stage 3 Python, Working with CSV & JSON

Written by

Muhammad Atif

Last Updated

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:

Python
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:

Python
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:

Python
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:

Python
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

  1. Read a CSV file containing user information and calculate the average age of the users.
  2. Convert a JSON file containing a list of products and their prices to a CSV file.
  3. 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

Review Questions

  1. What are the differences between CSV and JSON file formats?
  2. 2. How do you read and write CSV files using Python’s 'csv' module?
  3. How do you read and write JSON files using Python’s 'json' module?
  4. 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!

Muhammad Atif

Data Analyst & Web Development Professional | Focused on Machine Learning, SQL and Python

Transitioned from a background in finance to IT, I now focus on data science and web development, with specialties in Machine Learning, SQL, and Python. My articles aim to clarify complex IT concepts, informed by a rich history in analytical thinking and strategy.

You Might Also Like

Browse more topics and insights handpicked just for you. Stay updated and informed with our latest articles and news.