"

5 Culturally Relevant Pedagogy in Computing Education: File I/O

Adelina Patlatii; Moeez Omair; and Rutwa Engineer

This module teaches the basics of data manipulation using File I/O operations by performing tasks such as reading, writing, and manipulating CSV files, with a focus on ethical and culturally relevant applications. This approach aims to make your learning experience resonate with your diverse backgrounds and personal experiences, promoting inclusivity, equity, and ethical awareness in computing, and preparing you to consider the broader impact of your work in diverse societal contexts.

If you would like to try out the optional experiments included, please download and open the required files in your IDE: [Download Here]

Learning Objectives

  • Understand the basics of File I/O in Python
  • Gain familiarity with Python’s CSV module
  • Appreciate the significance of File I/O operations through applications that promote diversity, inclusivity, and ethical practices in computing

Basics of File I/O in Python

File I/O – File I/O is shorthand for Input/Output, which consist of operations to read and write files. These operations may be utilized in the context of data storage, data analysis, and various forms of data processing. Before we can work with a file, we must tell Python how to open it depending on our purpose (i.e., reading from it, or writing into it, etc.), which we can achieve through file modes:

  • Read  (‘r’): Opens a file for reading.
  • Write  (‘w’): Opens a file for writing, creating it if it doesn’t exist or truncating it if it does.
  • Append  (‘a’): Opens a file for writing, appending to the end if it exists.

These modes are specified in the parameters of the open() function. An example of opening a file for reading:

f = open('file.txt', 'r')

Here are the commonly used functions for reading from and writing into a file:

  • open(): Opens a file and returns a file object.
  • read(): Reads the entire content of a file.
  • readline(): Reads a single line from a file.
  • readlines(): Reads all lines in a file and returns them as a list.
  • write(): Writes a string to a file.
  • writelines(): Writes a list of strings to a file.
  • close(): Closes the file.

Let us see how we can use the knowledge gained so far in a real-world context: organizing a culinary event. Throughout this module, you will be creating a menu of the highly requested traditional dishes. The following tasks will guide you through the creation process.

Optional Experiment 1

Filtering Input By Given Parameters

Pre-requisite: make sure you have downloaded the required files from the link posted above. [Also here for quick access]

Let’s suppose that, when signing up for this event, each guest was prompted to select a traditional dish from a list of options that they were most interested in trying. The dishes themselves, together with the number of votes that each dish has accumulated are stored in the e1_dishes_by_votes.txt file.

Here is a glimpse of what the file looks like:

e1_dishes_by_votes.txt

Poutine:5
Carbonara:15
Ratatouille:7
Paella:10
Khachapuri:4
Injera:2
Borscht:3
Sushi:20
Tandoori Chicken:5
Falafel:10

Due to the limited resources, the event organizers are able to offer only the most popular dishes at the event. We have been tasked with selecting the dishes which have accumulated at least 10 votes, and writing them to an output file called e1_filtered_dishes.txt. This exercise aims to help you understand basic file reading and writing operations while engaging in a real-world problem.

The .py file and e1_dishes_by_votes.txt file are both located in the same folder, thus we would only need to provide the input file name alone as the first parameter of the open() function (instead of a relative path to the file). Here are the steps for implementing the filtering:

Step 1: Open the source file for reading.
source_file = open('e1_dishes_by_votes.txt', 'r')
Step 2: Create and open a destination file for writing.

destination_file = open('e1_filtered_dishes.txt', 'w')

Step 3: Assign the file reader to a variable.

line = source_file.readline()

Step 4: Read and filter the quotes. 

while line:

dish, score = line.split(':')
if int(score) >= 10:
destination_file.write(f'{dish}\n')
line = source_file.readline()
Step 5: Close both files. 

source_file.close() 
destination_file.close()

You may play around with the required score as you wish!

File I/O: CSV Files

Now that you have an idea of how to handle simple file I/O, let us consider a common data storage format: CSV Files.

CSV (Comma-Separated Values) Files – these are simple text files that store tabular data. Each line in a CSV file represents a row in the table, and each value within that row is separated by a comma. They are widely used for storing and exchanging data due to their simplicity and compatibility with various applications. CSV Files are especially useful for data analysis tasks, allowing easy manipulation and processing of large datasets. Understanding how to work with them is crucial for handling real-world data effectively.

Before we dive into the next activity, let us introduce the csv.DictReader() class:

The csv.DictReader() class in Python’s csv module is used to read CSV files and convert each row into a dictionary. The keys of the dictionary are the column headers from the first row of the CSV file, and the values are the corresponding data from each subsequent row.

Optional Experiment 2

Retrieving and Storing Data

Pre-requisite: make sure you have downloaded the required files from the link posted above. [Also here for quick access]

We are given a dataset of cultural foods with columns representing Name, Rating, Origin, Category, Vegetarian, Halal, and Gluten-Free.

Here is a glimpse of what the file looks like:

e2_cultural_foods.csv

Name,Rating,Origin,Category,Vegetarian,Halal,Gluten-Free
Sushi,4.8,Japan,Main Course,no,no,yes
Tacos,4.5,Mexico,Main Course,yes,no,no
Croissant,4.7,France,Bakery,yes,no,no
Pad Thai,4.6,Thailand,Main Course,yes,yes,no
Gelato,4.9,Italy,Dessert,yes,yes,yes
Falafel,4.3,Middle East,Main Course,yes,yes,yes
Poutine,4.2,Canada,Main Course,no,no,no
Biryani,4.7,India,Main Course,no,yes,no
Baklava,4.4,Turkey,Dessert,yes,yes,no
(...40 more rows...)
Please note that these cultural foods are not representative of all options, but rather a sample of fifty for this exercise.
Suppose we are interested in selecting a dish which aligns with our dietary restrictions of vegetarian and halal. Using the code in the following steps, we can filter and save dishes which fit the criteria into an output txt file:
Step 1: Import the Python csv library
import csv
Step 2: Open the source file for reading.
source_file = open('e2_cultural_foods.csv', 'r')
Step 3: Open the destination file for writing.
destination_file = open('e2_foods_veg_halal.txt', 'w')
Step 4: Assign the file reader to a variable. This allows us to read a csv file as a dictionary.
reader = csv.DictReader(source_file)
Step 5: Read and filter the quotes. 
for row in reader:
# Filtering for vegetarian and halal, treating each row as a dictionary
if (row['Vegetarian'] == "yes") and (row['Halal'] == "yes"):
# Each row is a dictionary
destination_file.write(f'{row["Name"]}\n')
Step 6: Close the files

source_file.close() 
destination_file.close()

You may experiment with the filters as you wish!

 

License

Culturally Relevant Pedagogy in Computing Education: File I/O Copyright © by Adelina Patlatii; Moeez Omair; and Rutwa Engineer. All Rights Reserved.