MGU Computer Science Series — Computer Science Foundations
Part III: Data and Algorithms
Files · Tables · CSV · Filtering · Sorting · Data Ethics
Chapter 14 of 28
MGU Computer Science Series  ·  Computer Science Foundations  ·  Library Textbook Edition

Chapter 14:
Files, Tables,
and Data Processing

Files, folders, paths, plain text, CSV tables, reading and writing data, cleaning, filtering, sorting, summarizing, and the responsible use of data about real people

■ CS Level: Foundations ■

■ 10 Sections  •  Part III of 7 ■

Follows Chapter 13: Abstraction, Models, and Simulation  ·  Prepares students for Chapter 15: Hardware and Computer Architecture

Purpose and Overview

Every time you save a document, submit a form, purchase something online, or check your grades, a program is reading or writing data stored in a file or database. Variables hold information while a program runs — but the moment the program stops, all of that information vanishes unless it was written somewhere persistent. Files solve this problem. They are the connective tissue that holds real software systems together, and understanding them is one of the most practical skills in computing.

This chapter introduces how programs store, read, write, and process data that persists beyond a single program run. You will learn what files are, how file systems organize them into trees of folders, and how paths describe where any file lives. You will explore plain text files and the CSV format for tabular data — two of the most common data formats in computing. You will trace the read-process-write pattern that most data programs follow, practice cleaning messy data, filter and sort records, and compute summaries that describe datasets as a whole. The chapter closes by addressing the ethical responsibilities that arise whenever programs handle data about real people.

These skills connect directly to databases, data science, web development, and software engineering — all courses that build on this foundation. By the end of this chapter, you should be able to work confidently with files and tables, trace data programs step by step, and think carefully about the human consequences of data decisions.

Opening Question

A school stores records for every student: names, grades, scores, schedules, health notes, and contact information. All of this is saved in files on a server somewhere. When a teacher opens a gradebook, a program reads one of those files. When a student submits an assignment, a program writes to another. When an administrator generates a report, a program filters and summarizes thousands of rows. How does this actually work — and what responsibilities come with the power to read and change data about real students?

10Sections
9Objectives
23Key Terms
8+Code Examples

Learning Objectives

  1. 1Explain what files are, why programs need them, and how memory and storage differ.
  2. 2Read a file system path and describe what it points to, distinguishing absolute from relative paths.
  3. 3Describe plain text files and explain why they are useful across computing.
  4. 4Interpret a tabular dataset, identifying rows, columns, fields, headers, and records.
  5. 5Read and interpret a CSV file and explain how the format handles special cases.
  6. 6Trace the read-process-write pattern in a data program.
  7. 7Identify common data quality problems and describe how cleaning addresses them.
  8. 8Trace filtering, sorting, and summarizing operations on small datasets.
  9. 9Discuss the ethical principles that govern responsible data use and explain why they matter.

Sections at a Glance

Sections 14.1 – 14.3
Files, Folders, Paths, and Plain Text
Why Files Exist · File Systems · Paths · Plain Text Files · Reading and Writing

Why Programs Use Files

When a program runs, it stores information in variables. Variables live in memory — fast storage that holds values only while the program is running. The moment the program stops, all of that information disappears.

Think about what would happen if your word processor worked only with memory. You would type an entire document, close the program, and find nothing saved. Every photo editing app would forget your edits. Every spreadsheet would reset to blank. Games would have no save states. Email clients would show empty inboxes every time they opened.

Programs solve this problem using files. A file is a named collection of data stored on a persistent storage device — a hard drive, solid-state drive, USB drive, or similar medium. Persistent means the data survives when power is turned off.

The Four Essential Uses of Files
  • Save information so it lasts beyond the current program run.
  • Load information from a previous session or from another program.
  • Share information between programs running on the same machine or across a network.
  • Archive information for records, backups, legal requirements, or future use.

Almost every useful program you have ever interacted with reads or writes files in some form — documents, photos, music, logs, settings, databases, web pages, source code, and data exports are all stored as files. Understanding files is not optional knowledge in computing. Files are the connective tissue that holds persistent software systems together.

Memory vs. Storage

The distinction between memory and storage is worth making precise before going further.

PropertyMemory (RAM)Storage (Drive)
SpeedVery fastSlower
PersistenceTemporary (lost on power-off)Permanent (survives power-off)
Typical sizeGigabytes (smaller)Terabytes (much larger)
Cost per unitMore expensiveLess expensive
Used forActive program data, variablesFiles, databases, installed programs
Key Idea

When a program reads a file, it copies data from storage into memory so the CPU can process it quickly. When a program writes a file, it copies data from memory back to storage so it survives after the program ends.

Files, Folders, and Paths

Files do not float in isolation. They are organized using file systems — structures that let operating systems store, find, and manage millions of files efficiently. A folder, also called a directory, is a container for files and other folders. Folders nest inside folders, forming a tree-like structure. At the top of the tree is the root directory — the starting point for the entire file system.

On Windows systems, the root of each drive is identified by a letter followed by a backslash: C:\. On macOS and Linux systems, the root is simply /.

A Typical File System Tree
/ (root)
├── home/
│   └── student/
│       ├── documents/
│       │   ├── essay.txt
│       │   └── notes.md
│       ├── data/
│       │   ├── students.csv
│       │   └── scores.csv
│       └── programs/
│           └── grade_calculator.py
└── etc/
    └── config.txt

File Paths

A path is a description of where a file is located in the file system. Paths describe the route from the root (or from the current location) to the target file, moving through folders one level at a time.

Absolute paths start from the root and describe the full location. Relative paths start from the current working directory — wherever the program is currently located. The .. symbol means "go up one level toward the parent folder."

Absolute vs. Relative Paths
Absolute (Linux / macOS):   /home/student/data/students.csv
Absolute (Windows):         C:\Users\student\data\students.csv

Relative (from student/):   data/students.csv
Relative (from programs/):  ../data/students.csv   ← go up, then into data/

File Extensions

Most file names include an extension — a short suffix after a period that indicates the file type by convention.

ExtensionTypical meaning
.txtPlain text
.csvComma-separated values (tabular data)
.pyPython source code
.htmlWeb page markup
.jsonStructured data in JSON format
.jpgCompressed image
.mp3Compressed audio
.pdfPortable document format
Student Warning

Extensions are conventions, not enforced rules. A file named data.txt that actually contains an image will still look like a text file to programs trying to read it — and will likely cause an error. The extension describes what you intend the file to contain; it does not guarantee it.

Plain Text Files

The simplest kind of file is a plain text file. A plain text file stores a sequence of characters using a standard encoding such as UTF-8 (introduced in Chapter 4). There is no special formatting, no fonts, no embedded images — only characters.

Plain text files are used constantly in computing: source code in nearly every programming language, configuration files for servers and tools, log files recording what programs did and when, data files shared between programs, and documentation files like this one. The power of plain text is its simplicity. Any program that can read characters can read a plain text file. Plain text does not depend on any proprietary format or special software.

What Plain Text Looks Like

A Plain Text Log File
2024-09-01 08:14:22 User login: asmith
2024-09-01 08:15:03 File opened: report.csv
2024-09-01 08:16:45 File saved: report.csv
2024-09-01 08:22:11 User logout: asmith
A Plain Text Configuration File
username = student1
language = English
theme = dark
font_size = 14

Reading and Writing Plain Text in Python Style

# Reading: basic pattern
file = open("notes.txt", "r")   # "r" means open for reading
contents = file.read()           # read everything into a string
file.close()                     # close the file when done
print(contents)

# Safer pattern using 'with' (auto-closes on exit)
with open("notes.txt", "r") as file:
    contents = file.read()
    print(contents)

# Writing plain text
with open("output.txt", "w") as file:   # "w" means open for writing
    file.write("Hello, file system.\n")
    file.write("This is a second line.\n")
Student Warning — Overwriting Files

Opening a file with "w" erases its previous contents immediately. To add to an existing file without erasing it, use "a" (append mode) instead. Always double-check the mode before writing to important files.

Sections 14.4 – 14.5
Tabular Data and CSV
Tables · Rows · Columns · Fields · CSV Format · Reading CSV

Tables, Rows, Columns, and Fields

Much of the data programs work with is tabular — organized into rows and columns, like a spreadsheet or a database table. Consider a simple table of student records:

student_idnamegradescore
1001Amara Osei1087
1002Jin Park1193
1003Fatima Nkrumah1078
1004Liam Torres1295
1005Sofia Reyes1182
Parts of a Table

Columns (also called fields or attributes) represent categories of information. Each column has a name and holds one type of data: student_id, name, grade, score.

Rows (also called records) represent individual items — here, individual students. Each row contains one value per column.

Fields are the individual cells at the intersection of a specific row and column. The field at row 1002, column score, contains the value 93.

Headers are the labels in the first row that name the columns. Programs rely on headers to interpret data correctly.

This structure is fundamental. It appears in spreadsheets, database tables, CSV files, exported reports, data science datasets, and API responses. Understanding it is the starting point for nearly all data work in computing.

CSV Data at an Introductory Level

CSV stands for Comma-Separated Values. A CSV file is a plain text file where tabular data is represented by separating column values with commas and separating rows with newline characters. The student table above, stored as a CSV file, would look like this:

The Student Table as a CSV File
student_id,name,grade,score       ← header row (column names)
1001,Amara Osei,10,87
1002,Jin Park,11,93
1003,Fatima Nkrumah,10,78
1004,Liam Torres,12,95
1005,Sofia Reyes,11,82

The first line is the header row — the column names. Each following line is one data row — one record. CSV is one of the most common data formats in computing because it is simple (just characters, commas, and newlines), universal (readable by spreadsheets, databases, programming languages, and text editors), and compact (no formatting overhead).

Complications in CSV

Real CSV files are rarely as clean as the example above. Three common complications arise.

CSV Special Cases
Values containing commas → wrap the field in quotation marks:
1006,"Torres, Maria",12,90

Values containing quotation marks → double the quotes inside:
1007,Kai ""The Coder"" Kim,11,88

Missing values → comma is present but nothing appears between:
1008,,10,75    ← the name field is empty

Reading CSV in Python Style

Python has a built-in csv module that handles these complications automatically. DictReader reads each row as a dictionary, where keys are column names from the header row.

import csv

with open("students.csv", "r") as file:
    reader = csv.DictReader(file)    # reads header row automatically
    for row in reader:
        print(row["name"], row["score"])
Output for the sample file
Amara Osei 87 Jin Park 93 Fatima Nkrumah 78 Liam Torres 95 Sofia Reyes 82
Why DictReader?

Accessing fields by name (row["score"]) is clearer and less error-prone than accessing them by position (row[3]). If columns are ever reordered, named access still works; positional access breaks silently.

Sections 14.6 – 14.9
Reading, Writing, Cleaning, Filtering, Sorting, and Summarizing
Read-Process-Write · Data Cleaning · Filtering · Sorting · Summaries

Reading and Writing Data

Programs that work with data typically follow a pattern called read-process-write, sometimes called ETL (Extract, Transform, Load). The core idea is simple but fundamental: read data from a source, process it (clean, filter, transform, or calculate), then write results to a destination.

The Read-Process-Write Pattern
┌───────────────┐     ┌───────────────┐     ┌───────────────┐
│               │     │               │     │               │
│   SOURCE      │────▶│   PROCESS     │────▶│  DESTINATION  │
│               │     │               │     │               │
│ students.csv  │     │ clean         │     │ report.csv    │
│ database      │     │ filter        │     │ screen output │
│ network API   │     │ sort          │     │ database      │
│ user input    │     │ summarize     │     │ email / log   │
│               │     │ transform     │     │               │
└───────────────┘     └───────────────┘     └───────────────┘

This pattern appears in data science pipelines, database systems, web servers, financial systems, scientific computing, and everyday programs. Understanding it helps you read any data program, not just ones you write yourself.

Reading Line by Line

For large files, reading the entire file at once can waste memory. Reading line by line processes one row at a time.

with open("students.csv", "r") as file:
    for line in file:
        print(line.strip())    # strip() removes the trailing newline character

A Complete Read-Process-Write Example

This program reads student scores, adds 5 bonus points to each, and writes the updated records to a new file.

import csv

# Step 1: Read
students = []
with open("students.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        students.append(row)

# Step 2: Process
for student in students:
    original = int(student["score"])
    student["score"] = original + 5

# Step 3: Write
with open("students_updated.csv", "w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=["student_id", "name", "grade", "score"])
    writer.writeheader()
    writer.writerows(students)

print("Done. Updated scores written to students_updated.csv")
Pattern Recognition

Notice the three-stage structure: open for reading → loop through rows → modify records → open for writing → write results. This pattern scales from tiny programs to industrial data pipelines processing millions of records per day.

Cleaning Data

In an ideal world, every dataset would arrive perfectly organized, complete, and correctly formatted. In practice, real data is frequently messy. Data cleaning (also called data wrangling) is the process of identifying and fixing problems in a dataset before analysis or use. It is often the most time-consuming step in any data project.

Problem TypeExampleRisk if Ignored
Missing values1002,,11,93 — name is emptySkewed calculations; program crashes
Format mismatch9/1/24 vs 2024-09-01Data misread or rejected
Duplicate recordsSame row appearing twiceInflated counts and sums
Out-of-range valuesScore = 150 (max is 100)Incorrect analysis; wrong conclusions

Missing Values

A missing value occurs when a field contains no data for a particular record. Programs that encounter missing values must decide: skip the record, substitute a default value, flag it for human review, or halt with an error. The right choice depends on the context and the purpose of the data.

Inconsistent Formats

The same information might appear in different formats across records. Dates are a classic example: 2024-09-01, Sep 1, 2024, 9/1/24, and 01-09-2024 all represent the same date, but a program expecting one format will misread or reject the others. Other inconsistencies include capitalization, units, and abbreviations.

Cleaning in Python Style

import csv

cleaned = []
with open("students_raw.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        # Skip rows with missing names or scores
        if not row["name"] or not row["score"]:
            continue

        # Convert score to integer; skip if it fails
        try:
            score = int(row["score"])
        except ValueError:
            continue

        # Skip out-of-range scores
        if score < 0 or score > 100:
            continue

        # Standardize name capitalization
        row["name"] = row["name"].strip().title()

        cleaned.append(row)

print(f"Cleaned: {len(cleaned)} valid records")
The Cost of Dirty Data

Incorrect data produces incorrect conclusions no matter how sophisticated the analysis. A data scientist who skips cleaning and jumps straight to analysis is building conclusions on an unreliable foundation. Cleaning is unglamorous but essential.

Filtering and Sorting Data

Once data is clean, programs often need to filter it (keep only the records that meet a condition) or sort it (arrange records in a specific order). These two operations appear in almost every data program.

Filtering

Filtering means selecting records that satisfy a condition and discarding the rest. Filters can test a single field or combine multiple conditions.

# Filter: grade 10 students only
grade_10 = []
for student in students:
    if int(student["grade"]) == 10:
        grade_10.append(student)

# Filter: combined condition — grade 10 AND score above 80
for student in students:
    if int(student["grade"]) == 10 and int(student["score"]) > 80:
        print(student["name"])

Sorting

Sorting arranges records in ascending (low to high) or descending (high to low) order based on one or more fields. Python's sorted() function accepts a key argument that specifies how to compare records.

# Sort by score, highest first
sorted_students = sorted(students, key=lambda s: int(s["score"]), reverse=True)

for student in sorted_students:
    print(student["name"], student["score"])

# Multi-level sort: grade ascending, then score descending within each grade
sorted_students = sorted(
    students,
    key=lambda s: (int(s["grade"]), -int(s["score"]))
)
Output — sorted by score, highest first
Liam Torres 95 Jin Park 93 Amara Osei 87 Sofia Reyes 82 Fatima Nkrumah 78

Filtering and Sorting Together

Real programs usually combine filtering and sorting in sequence.

# Grade 11 students, sorted by score descending
grade_11_top = sorted(
    [s for s in students if int(s["grade"]) == 11],
    key=lambda s: int(s["score"]),
    reverse=True
)
The Negative Sign Trick

In a multi-level sort, the negative sign on a numeric field reverses the order for that field only. -int(s["score"]) sorts score from highest to lowest while leaving other fields in their default direction. This is a common Python idiom worth recognizing.

Summarizing Data

Beyond reading and filtering, programs often need to summarize data — computing statistics that describe the dataset as a whole rather than listing every individual record. Summaries appear in business reports, medical studies, school analytics, government statistics, and scientific research every day.

Counting, Sum, Average, Min, and Max

# Counting
total = len(students)
grade_10_count = sum(1 for s in students if int(s["grade"]) == 10)

# Sum and average
scores = [int(s["score"]) for s in students]
average_score = sum(scores) / len(scores)
print(f"Average: {average_score:.1f}")    # .1f = one decimal place

# Min and max
print(f"Lowest: {min(scores)}")
print(f"Highest: {max(scores)}")

Grouping

Grouping means computing summaries for each category separately — for example, the average score per grade level.

from collections import defaultdict

grade_scores = defaultdict(list)   # each grade maps to a list of scores

for student in students:
    grade = student["grade"]
    score = int(student["score"])
    grade_scores[grade].append(score)

for grade in sorted(grade_scores.keys()):
    scores = grade_scores[grade]
    avg = sum(scores) / len(scores)
    print(f"Grade {grade}: {len(scores)} students, average {avg:.1f}")
Output — grouped averages
Grade 10: 2 students, average 82.5 Grade 11: 2 students, average 87.5 Grade 12: 1 students, average 95.0
Section 14.10
Responsible Use of Data
Sensitive Data · PII · Re-identification · Six Principles · Data and Power · Developer Checklist

Responsible Use of Data

Data about people is not abstract. Behind every row in a student table is a real student. Behind every health record is a real patient. Behind every financial transaction is a real account holder. The people whose information appears in data files have interests, rights, and expectations that computing professionals are obligated to respect.

What Makes Data Sensitive

Some data is more sensitive than other data. Categories that require particular care include:

CategoryExamples
PII — Personally identifiable informationNames, addresses, phone numbers, email, government IDs, birth dates
Health and medicalDiagnoses, medications, mental health records, genetic data
FinancialIncome, credit history, debt, account numbers
LocationHome address, travel patterns, frequent locations
BehavioralPurchases, searches, browsing history, communications
Re-identification

Even data that seems harmless in isolation can become sensitive when combined. A dataset with no names but including home zip code, birth date, and gender can often be used to identify specific individuals — a problem called re-identification. Removing names from a dataset does not automatically make it anonymous.

Six Principles of Responsible Data Use

Responsible Data Principles
  • Collect only what is necessary. Gathering extra data "just in case" creates unnecessary risk.
  • Store data securely. Personal data needs appropriate permissions, encryption, and secure systems.
  • Use data only for its stated purpose. Data collected for one purpose does not automatically authorize other uses.
  • Respect consent. Collecting personal data often requires the knowledge and agreement of the people it describes.
  • Delete data that is no longer needed. Keeping data indefinitely increases the risk of harm if a breach occurs.
  • Be honest about errors. Acknowledge uncertainty and limitations rather than presenting results with false confidence.

Data and Power

Whoever holds data has power. A hospital holds data about patients' health. A school holds data about students' performance. A company holds data about customers' purchases and preferences. A government holds data about citizens' identities and behavior. This power creates responsibilities. When data is lost, stolen, sold without consent, or used in ways people did not agree to, real harm follows — people lose privacy, suffer discrimination, become targets of fraud, or find their histories used against them.

Computing professionals who handle data about real people operate in a field with genuine ethical stakes. The programs they write and the decisions they make have consequences for the people whose data they manage.

A Developer Checklist

Before building a program that collects or processes data about people, thoughtful developers ask:

Data Responsibility Checklist
□  What data do we actually need?
□  Where will it be stored, and who can access it?
□  How long will we keep it, and when will we delete it?
□  Are we collecting this data with users' knowledge and consent?
□  What could go wrong if this data were accessed by the wrong person?
□  Who is accountable if something goes wrong?
Legal Requirements

These questions are not only ethical concerns — they are increasingly legal requirements. Privacy laws in many regions create specific obligations for how personal data must be collected, stored, used, and protected. Ignorance of these obligations does not eliminate liability.

Chapter Summary

Key Terms Review

file
A named collection of data stored on a persistent storage device that survives when power is turned off.
file system
The structure an operating system uses to organize, store, and retrieve files on a storage device.
folder / directory
A container that holds files and other folders, forming a hierarchical tree structure.
root directory
The top-level folder in a file system hierarchy; the starting point for all absolute paths.
absolute path
A file path that begins at the root directory and describes the file's full location.
relative path
A file path that begins at the current working directory rather than the root.
file extension
A suffix on a file name (such as .csv or .txt) that indicates the file type by convention.
plain text file
A file that stores only characters using a standard encoding, with no special formatting.
tabular data
Data organized into rows and columns, like a spreadsheet or database table.
row / record
A single entry in a table, representing one item in the dataset.
column / field
A category of information in a table; each column holds one type of data across all records.
header row
The first row of a table or CSV file, containing the names of the columns.
CSV
Comma-Separated Values — a plain text format for tabular data using commas to separate fields and newlines to separate rows.
read-process-write
The standard pattern for data programs: read from a source, transform or analyze the data, write results to a destination.
data cleaning
The process of identifying and fixing problems in a dataset before analysis, including missing values, format inconsistencies, duplicates, and out-of-range values.
missing value
A field in a dataset that contains no data for a particular record.
filtering
Selecting only the records from a dataset that satisfy a specified condition, discarding the rest.
sorting
Arranging records in a specified order — ascending or descending — based on one or more fields.
summarizing
Computing aggregate statistics — counts, sums, averages, minimums, maximums — that describe a dataset as a whole.
grouping
Computing summaries separately for each category within a dataset.
PII
Personally identifiable information — data that can be used to identify a specific individual, such as name, address, or government ID number.
re-identification
The process of identifying specific individuals from a dataset that lacks explicit names, by combining multiple fields.
data ethics
The principles and responsibilities that govern how data about people should be collected, stored, used, and protected.

Diagram Review

File System Tree with Paths
/ (root)
├── home/
│   └── student/
│       ├── data/
│       │   ├── students.csv    ←  /home/student/data/students.csv  (absolute)
│       │   └── scores.csv
│       └── programs/
│           └── process.py      ←  /home/student/programs/process.py (absolute)
└── etc/
    └── config.txt

From programs/, the relative path to students.csv is:   ../data/students.csv
  ( .. moves up to student/ → then data/ → then students.csv )
CSV Structure — Rows, Columns, and Fields
student_id , name              , grade , score    ← header row (column names)
-----------   -----------------   -----   -----
1001       , Amara Osei        , 10    , 87       ← row 1 (record 1)
1002       , Jin Park          , 11    , 93       ← row 2 (record 2)
1003       , Fatima Nkrumah    , 10    , 78       ← row 3 (record 3)
  ↑                ↑               ↑       ↑
field 1          field 2         field 3  field 4

Each cell (row ∩ column) is one field value.
The field at row 1002, column "score" = 93.

Code Review

Exercise 14.1 — Trace the output
What does this program print? Trace it step by step.
students = [
    {"name": "Mia", "grade": "10", "score": "72"},
    {"name": "Leo", "grade": "11", "score": "88"},
    {"name": "Zara", "grade": "10", "score": "91"},
]
for s in students:
    if int(s["grade"]) == 10:
        print(s["name"], int(s["score"]) + 5)
Exercise 14.2 — Find the error
This program intends to print students sorted from highest to lowest score. What is wrong?
sorted_students = sorted(students, key=lambda s: int(s["score"]))

for s in sorted_students:
    print(s["name"], s["score"])
Exercise 14.3 — Explain the purpose
What does strip() do, and why is it useful when reading lines from a file?
with open("notes.txt", "r") as file:
    for line in file:
        print(line.strip())
Exercise 14.4 — Predict the output
Given this CSV data, what does the program print?
scores.csv
name,score
Alice,85
Bob,92
Carol,78
import csv

scores = []
with open("scores.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        scores.append(int(row["score"]))

print(min(scores))
print(max(scores))
print(sum(scores) / len(scores))

Worked Example Review

Worked Example 14.1
Filtering Grade 11 Students with Score Above 85
  • ProblemGiven the student list, print only the names of grade 11 students whose score exceeds 85. Print results in alphabetical order by name.
  • PlanFilter for grade 11 AND score > 85. Sort by name. Print names.
  • Code filtered = [] for s in students: if int(s["grade"]) == 11 and int(s["score"]) > 85: filtered.append(s) filtered_sorted = sorted(filtered, key=lambda s: s["name"]) for s in filtered_sorted: print(s["name"])
  • TraceJin Park: grade 11, score 93 — qualifies. Sofia Reyes: grade 11, score 82 — score does not exceed 85, excluded.
Output: Jin Park
Worked Example 14.2
Computing a Grade Distribution
  • ProblemCount how many scores from a list fall in each letter-grade band (A: 90–100, B: 80–89, C: 70–79, D: 60–69, F: below 60) and print the results.
  • Code scores = [87, 93, 78, 95, 82, 65, 55, 91, 74, 88] counts = {"A": 0, "B": 0, "C": 0, "D": 0, "F": 0} for score in scores: if score >= 90: counts["A"] += 1 elif score >= 80: counts["B"] += 1 elif score >= 70: counts["C"] += 1 elif score >= 60: counts["D"] += 1 else: counts["F"] += 1 for grade, count in counts.items(): print(f"{grade}: {count}")
  • TraceScore 87: 87 ≥ 90? No. 87 ≥ 80? Yes → B. Score 93: 93 ≥ 90? Yes → A. And so on for each value.
A: 3  ·  B: 3  ·  C: 2  ·  D: 1  ·  F: 1

Concept Check

  1. What is the difference between a file and a variable? Why are files necessary?
  2. What does .. mean in a relative file path? Give an example.
  3. Why does CSV wrap some field values in quotation marks?
  4. What is the difference between filtering and sorting?
  5. Name three common data quality problems that data cleaning addresses.
  6. What does int(row["score"]) do, and why might it raise an error?
  7. What is re-identification, and why does it matter for privacy?
  8. In the read-process-write pattern, what happens during the process step?

Practice Questions

Practice 14.1Path Identification

Identify each as an absolute path or a relative path. Explain how you can tell.

  1. /home/student/data/grades.csv
  2. data/grades.csv
  3. ../reports/summary.txt
  4. C:\Users\admin\desktop\notes.txt
Practice 14.2CSV Interpretation

Read this CSV data and answer the questions.

employee_id,department,salary,years
E001,Engineering,72000,3
E002,Marketing,58000,7
E003,Engineering,81000,5
E004,HR,54000,2
E005,Marketing,61000,4
E006,Engineering,94000,9
  1. How many rows of data are in this table, not counting the header?
  2. How many columns does it have? Name them.
  3. What is the salary of employee E003?
  4. Which department has the most employees in this dataset?
  5. What is the average salary across all six employees?
Practice 14.3Filtering Conditions

Describe in plain English what each condition selects from a student dataset.

  1. int(s["score"]) >= 90
  2. s["grade"] == "12"
  3. int(s["score"]) > 70 and int(s["score"]) < 85
  4. s["name"].startswith("A")
Practice 14.4Sorting

Answer both parts without using a computer.

  1. Put these names in alphabetical (ascending) order: Torres, Osei, Nkrumah, Park, Reyes
  2. Put these scores in descending order (highest first): 78, 95, 87, 82, 93
Practice 14.5Summary Calculations

Use these scores. Show your arithmetic.

Scores: 91, 76, 84, 63, 88, 72, 95, 80, 68, 77

  1. Count: how many scores?
  2. Sum: what is the total?
  3. Average: sum ÷ count?
  4. Minimum: lowest score?
  5. Maximum: highest score?
  6. Filtered count: how many are above 80?
Practice 14.6Data Cleaning Scenario

Identify every data quality problem in this CSV. For each, name the type and describe the specific issue.

student_id,name,grade,score
1001,Marcus Chen,10,87
1002,,11,93
1003,Layla Hassan,10,78
1003,Layla Hassan,10,78
1004,Raj Patel,12,115
1005,amara osei,11,82
1006,Sofia Torres,9/1/2008,74
  1. List every problem you can find. For each: name the type (missing value, duplicate, format inconsistency, or out-of-range) and describe what is wrong.
Practice 14.7Ethics Scenario

A school stores a CSV file containing student names, home addresses, parent contact information, health conditions, and academic records.

  1. Which fields would you classify as sensitive personal data? Why?
  2. Who should be allowed to access this file? Who should not?
  3. What risks would arise if this file were accidentally made publicly accessible?
  4. When might it be appropriate to delete records from this file?
  5. If a researcher wanted to study the relationship between health conditions and academic performance, what ethical questions would need to be addressed before sharing the data?

Debugging and Error Analysis

Debug 14.1 — Average calculation crashes on some files
import csv total = 0 count = 0 with open("scores.csv", "r") as file: reader = csv.DictReader(file) for row in reader: total += int(row["score"]) count += 1 average = total / count print(f"Average: {average}")

What causes this program to crash? Identify two separate scenarios and describe how to fix each. Hint: what happens if the file is empty? What if a score field contains a non-numeric value?

Debug 14.2 — Filter produces no output
students = [ {"name": "Amara Osei", "grade": "10", "score": "87"}, {"name": "Jin Park", "grade": "11", "score": "93"}, ] for s in students: if s["grade"] == 10: ← look carefully here print(s["name"])

There are grade 10 students in the list, but nothing prints. Find the bug. Explain why it causes silence rather than an error message.

Debug 14.3 — Output CSV file is empty
import csv results = [] with open("students.csv", "r") as file: reader = csv.DictReader(file) for row in reader: if int(row["score"]) > 85: results.append(row) with open("high_scorers.csv", "w") as file: writer = csv.DictWriter(file, fieldnames=["student_id", "name", "grade", "score"]) # what is missing here? writer.writerows(results)

The output file exists but contains no readable data. What single line is missing? Where should it be inserted, and why is it needed?

Debug 14.4 — Malformed relative path
.././archive/old_data.csv

This path is supposed to point to a file two levels above the current folder, inside a folder called archive. What is wrong with it? Write the correct path.

Design and Application Questions

Design 14.1Table Design

Design a CSV table to store information about library books. The table must be able to answer these questions: Who is the author? What is the title? Is the book currently checked out? When is it due back? How many times has it been borrowed this year?

  1. Write out the column names you would use.
  2. For each column, state what type of data it holds (text, number, date, or yes/no).
  3. Write two sample rows of data that would fit your design.
Design 14.2Cleaning Checklist

A program will receive a CSV file of product inventory data from an external supplier. The file contains product names, prices, quantities, and category codes.

  1. Write a cleaning checklist of at least five specific checks the program should perform before using this data. For each check, explain what problem it catches and what the program should do when it finds one.
Design 14.3Pipeline Description

Describe in plain English — not code — a complete read-process-write pipeline that reads a CSV file of employee records (name, department, salary, years of service), removes records with missing values, filters for employees with more than 3 years of service, calculates the average salary for each department, and writes a summary CSV with one row per department.

  1. Write out each stage (read, process steps, write) in your own words.
  2. What columns would the output CSV file contain?
  3. How many rows would the output have, given the input described?

Real-World Applications

Application 14.1Log Files

Web servers generate log files recording every request they receive. A typical log line:

2024-09-15 14:22:03 192.168.1.45 GET /index.html 200 1543

This records: date and time · visitor IP address · request type · page requested · status code (200 = success) · bytes transferred.

  1. What questions could a developer answer by analyzing a log file?
  2. What data cleaning steps might be needed before analyzing logs at scale?
  3. A website gets 50,000 log entries per day. What summary statistics would be most useful?
  4. What privacy concerns arise from storing IP addresses in log files?
Application 14.2Health Records
  1. Why would a clinic export data to CSV rather than always analyzing directly in the database?
  2. Which fields in medical records would you classify as highly sensitive?
  3. If a researcher wants to study which medications are most commonly prescribed, how could the data be anonymized before sharing?
  4. If an error in the data showed a patient had been prescribed the wrong medication, what should happen — technically and ethically?
Application 14.3Search Engines
  1. What data would a search engine need to store for each indexed web page?
  2. How is filtering relevant when a user submits a search query?
  3. How is sorting relevant when displaying search results?
  4. What data quality problems might arise when indexing pages from across the entire web?

Mixed Review

  1. From Chapters 3 and 5. Describe in pseudocode an algorithm that reads a list of numbers and prints only those greater than a specified threshold. Include inputs, outputs, and the main steps.
  2. From Chapter 8. A loop reads records from a file one at a time. What type of loop would you use — a for loop or a while loop? Explain your choice.
  3. From Chapter 4. A CSV file uses UTF-8 encoding. What does that mean? Why does encoding matter when opening a file that may contain names from many languages?
  4. From Chapter 12. A CSV file has 1,000,000 records. A program needs to find all records where score > 90. Would this be faster if the records were pre-sorted by score? Explain using the concept of binary search.
  5. From Chapter 13. A data scientist builds a model using historical student data and warns the results might not generalize to students in other schools. How does the concept of model assumptions and limitations from Chapter 13 apply here?

Chapter 14 Checkpoint

Chapter 14 Checkpoint
Complete without assistance — assesses all key skills and concepts from Chapter 14
Section 1 — Vocabulary and Concepts
  1. Define file and explain how it differs from a variable.
  2. What is the difference between an absolute path and a relative path? Give one example of each.
  3. Name four common types of data quality problems that data cleaning addresses.
  4. What is re-identification, and why does removing names not automatically make data anonymous?
Section 2 — Paths and File Systems
  1. Given this file system, write the absolute path to report.csv:

    / → home/ → user/ → work/ → report.csv
  2. You are currently in /home/user/work/. Write a relative path to reach /home/user/data/scores.csv.
  3. What file type does the extension .csv indicate? Is this extension a guarantee about the file's contents? Explain.
Section 3 — Tables and CSV
  1. Identify the header row, data rows, columns, and a specific field value in this CSV:

    id,city,population
    1,Lagos,15000000
    2,Cairo,10000000
  2. Why does CSV wrap the value Torres, Maria in quotation marks when writing it to a file?
Section 4 — Data Operations
  1. Trace this code and write the exact output:

    data = [{"city":"A","pop":"50000"},{"city":"B","pop":"120000"},{"city":"C","pop":"30000"}]
    result = sorted(data, key=lambda d: int(d["pop"]), reverse=True)
    for r in result: print(r["city"])
  2. A dataset has scores: 88, 72, 95, 61, 84. Calculate the count, sum, average, minimum, and maximum by hand.
  3. Write a filtering condition (in Python-style pseudocode) that selects cities with a population greater than 100,000.
Section 5 — Ethics and Responsibility
  1. List three categories of data that are considered particularly sensitive. For each, give one example.
  2. A company collects customer email addresses for order confirmations and then uses them to send advertising without asking. Which principle of responsible data use does this violate?
  3. A program that calculates salary statistics accidentally double-counts several employees due to duplicate records. What type of data quality problem is this, and how does it affect the results?
Looking Ahead
Chapter 15: Hardware and Computer Architecture

Chapter 14 focused on how programs handle data — reading, writing, cleaning, filtering, sorting, and summarizing files. All of this work happens on physical hardware: circuits, chips, drives, and connectors that actually store and move the bits. Chapter 15 introduces the physical components of computing systems — the CPU, memory, storage, input and output devices, buses, and the fetch-decode-execute cycle. Understanding hardware explains why programs behave the way they do: why some operations are fast and others slow, why memory fills up, why storage and memory are different kinds of resources, and why the physical world eventually constrains every software system.

MGU Library Connection
  • File Paths and File Systems Reference — Appendix G of this textbook
  • Python-Style Code Reference — Appendix D of this textbook (file I/O section)
  • Data Structures Reference — Appendix F of this textbook (lists and dictionaries)
  • Databases and Information Systems — Chapter 18 of this textbook (extends tabular data to relational databases and SQL)
  • Data Science Foundations — Chapter 25 of this textbook (extends summarizing to statistics and visualization)
  • MGU Computer Science Series: Python Programming Foundations — deeper file I/O, error handling, and CSV processing
  • MGU Computer Science Series: Databases and SQL Foundations — full treatment of relational data, queries, and transactions