YEAR 9 DIGITAL TECHNOLOGIES • PYTHON FILES
Working with CSV Files in Python
In this lesson, you will use Python file handling and the csv module to save, read, append, and modify data in a CSV file.
CONTEXT
CSV stands for comma-separated values. It is a common file format used to store data in rows and columns.
Unlike normal variables, data saved in a file can still be used after the program closes.
In Python, this means a program can write data into a CSV file, read it back later, add new rows, and update existing rows.
Your focus in this lesson is to learn the core file operations needed to work with a file such as logbook.csv or diary.csv.
LEARNING GOALS
- Create a CSV file.
- Write rows into the file.
- Read rows back into Python.
- Append new rows to the file.
- Modify an existing row by reading and rewriting the file.
KEY IDEAS
- A file can store data after the program ends.
- A CSV file stores data in rows and columns.
- Python uses file modes such as
"w","a", and"r". - The
csvmodule helps Python read and write CSV files correctly. - Appending adds new rows to the end of the file.
- Modifying a row usually means reading the whole file, changing the row, and saving the whole file again.
SUCCESS CRITERIA
- Your program can create a CSV file.
- Your program can write rows into the file.
- Your program can read rows back from the file.
- Your program can append a new row without deleting old rows.
- Your program can modify an existing row and save the changes.
- Your code and output are clear and readable.
PRACTICE TASKS
- Create a diary.csv file and save at least 2 diary entries.
- Write a program that reads the file and prints the number of entries.
- Modify one entry and save the updated version of the file.
REMEMBER
This lesson is about understanding how Python works with CSV files.
Keep the code simple, use the correct file mode, and check carefully that your file contains the rows you expect.