Week 13 Optional Exercise: File I/O Practice Ladder

Many of you said files, CSVs, paths, and the terminal still feel shaky. This lab is a ladder: six short levels, each building on the one before. Start wherever you feel comfortable and stop whenever you like. There is no grade. The goal is for file code to feel familiar instead of scary.

Before you start

  1. Make a new folder called file_practice.
  2. Download notes.txt and scores.csv from Canvas and put them in that folder.
  3. Save each level's program in the same folder as level1.py, level2.py, and so on.
  4. Run every level from the terminal, not with your IDE's Run button. Level 0 shows you how.

Terminal cheat sheet

The terminal is a way to talk to your computer by typing instead of clicking. Everything you do in a file explorer (open folders, look inside them, view files) you can also do here.

What you want to doMac / Linux / Windows PowerShellWindows Command Prompt
Where am I?pwdcd
What's in this folder?lsdir
Go into a foldercd folder_namecd folder_name
Go up one foldercd ..cd ..
Show what's inside a filecat file_nametype file_name
Run a Python programpython file_name.py (Mac may need python3)python file_name.py

Tips: Press the up arrow to bring back your last command. Press Tab while typing a file or folder name and the terminal will finish it for you.

How each level works

Every level (except Level 3) comes in three versions. Pick the one that fits how you feel today. You can switch at any time.

VersionWhat you getGood if you...
RearrangeAll the correct lines, scrambled. Put them in order.want to see working code before writing any
Fill in the blanksMost of the program, with key pieces missing (_____).understand the idea but forget the details
Write it yourselfJust the task and the expected output.want a real challenge

At every level, follow the same habits we've used all semester:

  1. Predict what the program will print before you run it. Write your prediction down.
  2. Run it.
  3. Compare your output to the expected output (click "Check your output").
  4. Break it on purpose and read the error message.

Working alone? You may ask an AI tool to explain an error message or explain a line of code. Do not ask it to write the program for you. If you need the answer, you won't learn the skill.

Working in class? Work in pairs. Switch who is typing at each new level.


Level 0: Terminal warm-up

Goal: Find your way to your file_practice folder and look at your files, using only the terminal. Everyone does the same steps for this level.

  1. Open a terminal. (In VS Code: Terminal → New Terminal.)
  2. Type pwd and press Enter. This shows the folder you're currently "standing in." Write it down.
  3. Type ls and press Enter. These are the files and folders where you're standing.
  4. Use cd to move toward your file_practice folder, one folder at a time. After each cd, type ls to see where you can go next. (If you get lost, cd .. moves you back up.)
  5. Once you're in file_practice, type ls. You should see notes.txt and scores.csv.
  6. Type cat notes.txt. The file's contents appear right in the terminal. No program needed.
  7. Type cat scores.csv. Notice: this is what a CSV file really looks like. No spreadsheet grid, just text with commas. This is exactly what Python sees when it opens the file.
  8. Type pwd again. How is it different from step 2?

Think about it: Every program you run from here will start "standing in" file_practice. Keep that in mind. It matters a lot in Level 3.


Level 1: Read a file and print it

Goal: Open notes.txt and print every line.

Rearrange

Put these lines in order. The indentation is a clue.

        print(line)
with open("notes.txt", "r") as notes_file:
    for line in notes_file:

Fill in the blanks

with _____("notes.txt", _____) as notes_file:
    for line in _____:
        print(line)

Write it yourself

Write a program that opens notes.txt for reading and prints each line using a for loop.

Predict: What will the output look like?

Run it from the terminal: python level1.py

Check your output
Bring laptop charger

Finish lab 12

Email project team

Notice the blank lines? Each line in the file ends with an invisible "newline" character, and print() adds another one. Change print(line) to print(line.strip()) and run it again. .strip() removes extra spaces and newlines from the ends of a string.

Break it: Change "notes.txt" to "note.txt" (missing the s). Run it. What is the name of the error? Which line does it point to?


Level 2: Write a file, then check it

Goal: Write three items to a new file called my_list.txt, then open it and print what's inside.

Rearrange

    print(list_file.read())
    list_file.write("bread\n")
with open("my_list.txt", "r") as list_file:
    list_file.write("milk\n")
with open("my_list.txt", "w") as list_file:
    list_file.write("apples\n")

Fill in the blanks

with open("my_list.txt", _____) as list_file:
    list_file._____("apples\n")
    list_file._____("bread\n")
    list_file._____("milk\n")

with open("my_list.txt", _____) as list_file:
    print(list_file._____())

Write it yourself

Write apples, bread, and milk to my_list.txt, each on its own line. Then reopen the file and print its contents.

Check your output
apples
bread
milk

Type ls in the terminal. my_list.txt should now be in the list. Python created it for you.

The mode experiment

Answer each prediction before running. After each run, type cat my_list.txt to see exactly what's in the file. (Remember: the up arrow brings back old commands, so you don't have to retype them.)

  1. Predict: If you run the program a second time with "w", how many lines will the file have? Run it and check.
  2. Change the first "w" to "a". Predict: If you run it now, how many lines will the file have? Run it and check.
  3. Predict: If you run it one more time, how many lines? Run it and check.
Check your thinking
  1. Still 3 lines. "w" (write) erases the file and starts fresh every time.
  2. 6 lines. "a" (append) keeps what's already there and adds to the end.
  3. 9 lines.

Break it: Delete my_list.txt from your folder, then type ls to confirm it's gone. Change the first "a" to "r" and run. What happens, and why does "w" not cause this problem?


Level 3: Paths and the terminal (an investigation)

Everyone does the same steps for this level. The goal is to answer two questions: Why does my program sometimes say it can't find a file that's right there? and What is the terminal actually for?

Part A: Files in folders

Do these steps in the terminal, not in your file explorer. Type pwd first to make sure you're standing in file_practice.

  1. Make a new folder: mkdir data (mkdir means "make directory." Directory is another word for folder.)
  2. Move notes.txt into it: mv notes.txt data (Command Prompt: move notes.txt data)
  3. Type ls. Then type ls data. Where is notes.txt now?
  4. Predict: What happens if you run python level1.py now? Run it.
  5. Change "notes.txt" to "data/notes.txt" in level1.py. Run it again.

"data/notes.txt" is a relative path. It means "starting from where I am, go into the data folder, then find notes.txt."

Part B: Where am I?

  1. Type pwd to confirm you're in file_practice, then run python level1.py. It should work.
  2. Now type cd data to move into the data folder. Type pwd and ls. What changed?
  3. Type cat notes.txt. The file is definitely here.
  4. Predict: What happens if you type python ../level1.py? (.. means "the folder above this one.") Run it.
Check your thinking

You get a FileNotFoundError, even though the file exists and the program hasn't changed.

A relative path is relative to where you are running the program from (called the current working directory), not where the .py file lives. You were standing inside data, so Python looked for data/data/notes.txt, which doesn't exist.

This is why the terminal matters. It shows you exactly where you are and lets you control it. Your IDE also runs programs from some folder. When a program works on one computer and not another, this is often why.

Part C: The absolute path fix

  1. You're still inside data. Type pwd. The terminal shows the full address of the folder you're standing in.
  2. The full address of notes.txt is that folder address plus /notes.txt at the end (Windows: \notes.txt). Copy the pwd output and add the filename.
  3. Paste that full path into level1.py in place of "data/notes.txt". On Windows, put an r in front of the quotes, like r"C:\Users\...\notes.txt".
  4. Run it from inside data again: python ../level1.py. Does it work now?
  5. Type cd .. to go back up to file_practice, then run python level1.py. Does it still work?

An absolute path is the file's full address, so it works no matter where you run from. The downside: it only works on your computer, because nobody else has your folder names.

Discuss or write down: When would you choose a relative path? When would you choose an absolute path?

Before moving on: Type pwd and make sure you're back in file_practice. Levels 4–6 expect you to start there.


Level 4: Read a CSV file

Goal: Read scores.csv, print each student's name, and print the class average.

Type cat scores.csv in the terminal and look at it again. What do you notice about the first line? How many lines are there, and how many of them are actual students?

Rearrange

        count = count + 1
import csv
    next(reader)
print("Average:", average)
total = 0
        name = row[0]
    for row in reader:
average = total / count
        score = int(row[1])
count = 0
with open("scores.csv", "r") as scores_file:
        total = total + score
    reader = csv.reader(scores_file)
        print(name)

Fill in the blanks

import _____

total = 0
count = 0
with open("scores.csv", "r") as scores_file:
    reader = csv._____(scores_file)
    _____(reader)               # skip the header row
    for row in reader:
        name = row[_____]
        score = _____(row[1])
        print(name)
        total = total + score
        count = count + 1

average = total / count
print("Average:", average)

Write it yourself

Using the csv module, read scores.csv, skip the header row, print each name, and print the average score.

Trace it

Before running, fill in this trace table. Each row of the table is one trip through the for loop.

Iterationrownamescoretotalcount
1
2
3
4

Hint: row is a list of strings. Iteration 1's row is ['Ava', '92'].

Check your output
Ava
Ben
Carmen
Dev
Average: 79.75

Notice that '92' (a string) became 92 (an int) because of int(). A CSV file is just text. Python doesn't know 92 is a number until you tell it.

Break it (do both, one at a time):

  1. Delete the next(reader) line. Predict what goes wrong, then run it. Read the error carefully. What word is Python trying to turn into a number?
  2. Put next(reader) back. Change int(row[1]) to just row[1]. Run it. What does the error say Python can't add together?

Level 5: CSV into a dictionary, then loop

Goal: Store every student's score in a dictionary (name → score), print the dictionary, then print the name of everyone who scored above 80.

Rearrange

        name = row[0]
    if score > 80:
import csv
for name, score in scores.items():
        scores[name] = score
scores = {}
    reader = csv.reader(scores_file)
        print(name, "scored above 80")
    for row in reader:
print(scores)
    next(reader)
        score = int(row[1])
with open("scores.csv", "r") as scores_file:

Fill in the blanks

import csv

scores = _____
with open("scores.csv", "r") as scores_file:
    reader = csv.reader(scores_file)
    next(reader)
    for row in reader:
        name = row[0]
        score = int(row[1])
        scores[_____] = _____

print(scores)
for name, score in scores._____():
    if _____:
        print(name, "scored above 80")

Write it yourself

Build a dictionary where each key is a student's name and each value is their score (as an int). Print the dictionary, then loop through it and print everyone who scored above 80.

Predict: What will print(scores) show? Write it out exactly, including the braces and quotes.

Check your output
{'Ava': 92, 'Ben': 78, 'Carmen': 85, 'Dev': 64}
Ava scored above 80
Carmen scored above 80

Look at the dictionary. The names have quotes (strings) and the scores do not (ints). That's the int() at work.

Break it: Change int(row[1]) to row[1]. Predict: Will print(scores) still work? Will the if still work? Run it and find out. What's different in the dictionary printout?

Think about it: Why is a dictionary a better choice here than two separate lists, one of names and one of scores?


Level 6 (stretch): Write a summary file

Goal: Add to your Level 5 program so it also writes the students above 80 to a new file called summary.txt, then reads the file back and prints it.

This level has no rearrange version. You've seen every piece before. Here's the fill-in version if you want it:

with open("summary.txt", _____) as summary_file:
    summary_file.write("Students above 80:\n")
    for name, score in scores.items():
        if score > 80:
            summary_file.write(name + ": " + _____(score) + "\n")

with open("summary.txt", "r") as summary_file:
    print(summary_file._____())
Check your output
Students above 80:
Ava: 92
Carmen: 85

You just built a full input → process → output program: data comes in from one file, gets processed, and goes out to another file.

Type ls to see that summary.txt exists, then cat summary.txt to check it without running any Python.

Break it: Remove the str() around score. What does the error say? Why does .write() care about types?

Terminal bonus: save output without writing any file code

The terminal can catch everything a program prints and save it to a file for you.

  1. Type python level5.py > results.txt and press Enter.
  2. Predict: Why didn't anything appear on the screen?
  3. Type ls. Then type cat results.txt.
  4. Run the same command again. Predict: Will results.txt have the output once or twice? Check with cat.
  5. Now try python level5.py >> results.txt (two arrows) and check again.
Check your thinking

> sends the printed output into a file instead of the screen. Like "w", it replaces the file every time. >> works like "a": it adds to the end.

This is one big reason people use the terminal: you can combine programs and files in seconds, without changing any code.

(If you're using Windows PowerShell and cat results.txt shows strange spacing, that's a PowerShell quirk with >, not a problem with your program.)


Before you leave (or before you close the lab)

Write down three short answers, the same way we've done all semester:

  1. Which level did you reach? (Did you switch versions along the way?)
  2. One thing that clicked today.
  3. One thing that still feels shaky.

If you're in class, hand these to me. If you're working at home, bring them to our next class.