0
0
Pythonprogramming~30 mins

Reading and writing CSV data in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading and writing CSV data
📖 Scenario: You work in a small bookstore. You have a list of books with their titles and prices. You want to save this list to a CSV file and then read it back to check the data.
🎯 Goal: Learn how to write a list of dictionaries to a CSV file and then read the CSV file back into a list of dictionaries using Python.
📋 What You'll Learn
Create a list of dictionaries with book data
Set the CSV filename in a variable
Write the list of dictionaries to a CSV file
Read the CSV file back and print the data
💡 Why This Matters
🌍 Real World
CSV files are a common way to store and share tabular data like product lists, contacts, or sales records.
💼 Career
Knowing how to read and write CSV files is important for data processing, reporting, and automation tasks in many jobs.
Progress0 / 4 steps
1
Create the book data list
Create a list called books with these exact dictionaries: {'title': 'Python Basics', 'price': '29.99'}, {'title': 'Data Science', 'price': '39.99'}, and {'title': 'Web Development', 'price': '24.99'}.
Python
Need a hint?

Use square brackets [] to create a list and curly braces {} for dictionaries.

2
Set the CSV filename
Create a variable called filename and set it to the string 'books.csv'.
Python
Need a hint?

Use a simple string assignment like filename = 'books.csv'.

3
Write the books list to the CSV file
Import the csv module. Use open(filename, 'w', newline='') to open the file for writing. Create a csv.DictWriter with fieldnames ['title', 'price']. Write the header and then write all rows from books.
Python
Need a hint?

Remember to import csv and use DictWriter with the correct fieldnames.

4
Read the CSV file and print the data
Open the file filename for reading. Use csv.DictReader to read the rows. Convert the rows to a list called read_books. Print read_books.
Python
Need a hint?

Use csv.DictReader and convert the reader to a list before printing.