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
- Make a new folder called
file_practice. - Download
notes.txtandscores.csvfrom Canvas and put them in that folder. - Save each level's program in the same folder as
level1.py,level2.py, and so on. - 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 do | Mac / Linux / Windows PowerShell | Windows Command Prompt |
|---|---|---|
| Where am I? | pwd | cd |
| What's in this folder? | ls | dir |
| Go into a folder | cd folder_name | cd folder_name |
| Go up one folder | cd .. | cd .. |
| Show what's inside a file | cat file_name | type file_name |
| Run a Python program | python 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.
| Version | What you get | Good if you... |
|---|---|---|
| Rearrange | All the correct lines, scrambled. Put them in order. | want to see working code before writing any |
| Fill in the blanks | Most of the program, with key pieces missing (_____). | understand the idea but forget the details |
| Write it yourself | Just the task and the expected output. | want a real challenge |
At every level, follow the same habits we've used all semester:
- Predict what the program will print before you run it. Write your prediction down.
- Run it.
- Compare your output to the expected output (click "Check your output").
- 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.
- Open a terminal. (In VS Code: Terminal → New Terminal.)
- Type
pwdand press Enter. This shows the folder you're currently "standing in." Write it down. - Type
lsand press Enter. These are the files and folders where you're standing. - Use
cdto move toward yourfile_practicefolder, one folder at a time. After eachcd, typelsto see where you can go next. (If you get lost,cd ..moves you back up.) - Once you're in
file_practice, typels. You should seenotes.txtandscores.csv. - Type
cat notes.txt. The file's contents appear right in the terminal. No program needed. - 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. - Type
pwdagain. 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.)
- Predict: If you run the program a second time with
"w", how many lines will the file have? Run it and check. - Change the first
"w"to"a". Predict: If you run it now, how many lines will the file have? Run it and check. - Predict: If you run it one more time, how many lines? Run it and check.
Check your thinking
- Still 3 lines.
"w"(write) erases the file and starts fresh every time. - 6 lines.
"a"(append) keeps what's already there and adds to the end. - 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.
- Make a new folder:
mkdir data(mkdirmeans "make directory." Directory is another word for folder.) - Move
notes.txtinto it:mv notes.txt data(Command Prompt:move notes.txt data) - Type
ls. Then typels data. Where isnotes.txtnow? - Predict: What happens if you run
python level1.pynow? Run it. - Change
"notes.txt"to"data/notes.txt"inlevel1.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?
- Type
pwdto confirm you're infile_practice, then runpython level1.py. It should work. - Now type
cd datato move into thedatafolder. Typepwdandls. What changed? - Type
cat notes.txt. The file is definitely here. - 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
- You're still inside
data. Typepwd. The terminal shows the full address of the folder you're standing in. - The full address of
notes.txtis that folder address plus/notes.txtat the end (Windows:\notes.txt). Copy thepwdoutput and add the filename. - Paste that full path into
level1.pyin place of"data/notes.txt". On Windows, put anrin front of the quotes, liker"C:\Users\...\notes.txt". - Run it from inside
dataagain:python ../level1.py. Does it work now? - Type
cd ..to go back up tofile_practice, then runpython 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.
| Iteration | row | name | score | total | count |
|---|---|---|---|---|---|
| 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):
- 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? - Put
next(reader)back. Changeint(row[1])to justrow[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.
- Type
python level5.py > results.txtand press Enter. - Predict: Why didn't anything appear on the screen?
- Type
ls. Then typecat results.txt. - Run the same command again. Predict: Will
results.txthave the output once or twice? Check withcat. - 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:
- Which level did you reach? (Did you switch versions along the way?)
- One thing that clicked today.
- 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.