ENSA-Kenitra Module : Compétence Numériques
Lab 8: Python File Handling:
Introduction to CSV Files for Data Analysis
Exercise 1: Using writerow and writerows
In this exercise, you will practice reading and writing CSV (Comma Separated Values) files
using Python’s built-in csv module, providing a foundation for future data analysis tasks.
Write a Python program that:
1. Creates a CSV file named student_grades.csv.
2. Writes the following header and data into the file, using csv.writer, writerow for the
header and writerows for the data:
Name,Age,Grade,Subject
Ahmed,20,19,Math
Amal,22,18,Physics
Morad,21,15,Chemistry
Sophia,23,13,Biology
Yassmine,22,16,Math
3. Reads the CSV file and prints each row to verify the data.
4. Calculates and prints the average grade of all students.
5. Appends a new student's information to the CSV file.
6. Reads the updated file and prints it again, verifying the new student entry.
Exercise 2: Using DictWriter and DictReader
Write a Python program that:
1. Creates a CSV file named employees.csv.
2. Uses the csv.DictWriter to write the header and data for a list of employees, where
each employee has the fields: EmployeeID, Name, Department, and Salary.
3. Writes the following data using DictWriter:
{'EmployeeID': 1, 'Name': 'Ali', 'Department': 'HR', 'Salary':
5500}
{'EmployeeID': 2, 'Name': 'Ahmed', 'Department': 'Engineering',
'Salary': 7500}
{'EmployeeID': 3, 'Name': 'Iyad', 'Department': 'Marketing',
'Salary': 6000}
{'EmployeeID': 4, 'Name': 'Rania', 'Department': 'Engineering',
'Salary': 7200}
{'EmployeeID': 5, 'Name': 'Kevin', 'Department': 'Sales',
'Salary': 4800}
4. After writing, opens the CSV file and prints each row using DictReader to verify the
data.
5. Displays only all the employees’ names and salary information: e.g.:
Employee Name: Kevin, Employee Salary: 4800
Pr. Mehdia AJANA Chapter6 – Python: File Handling 1