Python Practice Set (Part 18): Working with CSV Files
- Anubhav Somani
- Sep 3
- 2 min read

Handling Data Like a Pro: A Guide to Reading and Writing CSV Files in Python
Welcome to Part 18 of our Python practice series! A huge amount of the world's data is stored in Comma-Separated Values, or CSV files. These simple text files are the backbone of data exchange for everything from spreadsheets to databases. Knowing how to read, process, and write CSV files is a non-negotiable skill for any data-focused programmer. In this set, we'll master Python's built-in csv module to handle tabular data with ease.
1. Reading a CSV File
Let's start by reading a simple CSV file. First, create a file named employees.csv with the following content:
Code snippet
Name,Department,Salary
John Doe,Sales,60000
Jane Smith,Marketing,65000
Peter Jones,IT,70000
Now, write a function read_employee_data that opens this file, reads its contents using the csv module, and prints each row as a list.
2. Reading a CSV into Dictionaries
Printing rows as lists is good, but accessing data by column name is even better. The csv.DictReader is perfect for this. Write a function read_employee_as_dicts that reads the same employees.csv file but converts each row into a dictionary. Print the list of dictionaries.
3. Writing Data to a CSV File
Now let's create a CSV file from scratch. You have the following data as a list of lists: data_to_write = [ ['ProductID', 'ProductName', 'Price'], ['101', 'Laptop', '1200'], ['102', 'Mouse', '25'], ['103', 'Keyboard', '75'] ] Write a function write_product_data that takes this data and writes it to a new file called products.csv.
4. Filtering Data from a CSV File
This task combines reading and processing. Using the employees.csv file from the first question, write a function find_high_earners that reads the file and prints the Name and Salary of only the employees who earn more than 65000.
Hint: You'll need to read the data, skip the header row, and convert the salary string to an integer for comparison.
5. Appending a Row to an Existing CSV
You need to add a new employee to your employees.csv file without deleting the existing data. Write a function add_new_employee that takes a new employee's data as a list (e.g., ['Susan May', 'HR', '58000']). The function should open employees.csv in append mode and add this new row to the end.
Comments