Paths and Text Files

files-and-data
Find files reliably and read or write plain text safely.
  • Level: Beginner to intermediate
  • Estimated time: 35–50 minutes
  • You will learn: Find files reliably and read or write plain text safely.
  • Practice in: VS Code, Jupyter, and local files

Questions

  • What problem does Paths and Text Files help us solve in a small Python program?
  • What should we predict before running the example?
  • What value, output, or error should we inspect after changing one line?

Objectives

  • Run a complete example for paths and text files in Colab.
  • Explain the example line by line using plain language.
  • Change one part of the code and predict the result before running it.
  • Recognize one common mistake and use the error message as evidence.

Hands-on episode: Paths and Text Files

A path points to a file or folder. open connects your program to a file, and a with block makes sure the file is closed even if something goes wrong.

We will learn this by running code, not by memorizing a definition first. Open the Colab notebook from the button above, find this section, and run each cell in order. Keep a small note beside the notebook with three columns: prediction, actual result, and what changed.

Example 1.1

Predict what file will be created and what text will be read back.

from pathlib import Path

path = Path("notes.txt")
path.write_text("Practice one idea at a time.
")
message = path.read_text()
print(message)

Run the cell once without editing it. If the result is different from your prediction, leave the prediction visible and write one sentence about the difference. That sentence is more useful than a perfect first guess.

Explain Example 1.1

  • Path("notes.txt") creates a path relative to the current working directory.
  • write_text stores text in that file, replacing old content if the file already exists.
  • read_text loads the file contents back into Python as a string.
  • The print call displays the text so you can verify the round trip.

Now explain the example out loud or in a Markdown cell. Use short sentences: “this line creates…”, “this name stores…”, “this output appears because…”. If you cannot explain a line yet, run only the lines above it and inspect the values that exist at that moment.

Challenge 1.1

NoteChallenge

Change the file name to data/notes.txt before creating the data folder. The error tells you the folder path does not exist yet, which is different from the file contents being wrong.

Show a safe way to approach the challenge
  1. Copy Example 1.1 into a new Colab cell.
  2. Change exactly one value, name, condition, or line.
  3. Write the expected output before running the cell.
  4. Run the cell and compare the actual result with your prediction.
  5. If the result surprises you, undo the change and try a smaller one.

Suggested first move: Change the file name to data/notes.txt before creating the data folder.

Debugging checkpoint 1.1

WarningDebugging checkpoint

When Python cannot find a file, first print the current working directory and the path you are using. Many file bugs are location bugs. Be careful with write mode because it can overwrite a file that already exists.

Do not debug by rewriting the whole example. Read the error type or surprising output, inspect the closest value with print(...) or type(...), then change one thing. This is the same routine you will use in larger projects.

Apply it

In Colab, write a short journal entry to a text file, read it back, append one more line, and print the final contents. Explain which line creates data and which line preserves it.

Finish by adding a Markdown cell that answers: What did this example teach me that I can reuse in a project?

Key points

  • Learn the concept by running a complete, small example first.
  • Predict before execution so your thinking becomes visible.
  • Change one thing at a time so cause and effect stay clear.
  • Treat errors as clues about the exact line or value Python could not handle.

Why this matters

Find files reliably and read or write plain text safely.

This lesson combines related subtopics that belong together in one learning conversation. You will still pause for a quiz after each section, but you do not need to jump between separate pages while building one clear explanation.

NoteGuiding questions

By the end of this lesson, you should be able to answer:

  • How do the sections in Paths and Text Files fit together?
  • Which small example demonstrates each section?
  • Which debugging clue should I check first for each section?
NoteLearning objectives

You will practice how to:

  • explain the shared concept for this lesson;
  • use each section as one step in a larger workflow;
  • complete 3 short section quizzes before moving on;
  • connect examples, mistakes, and debugging routines.

Lesson map

  • 1. Paths and Working Directories — Find files reliably using paths and the current working directory.
  • 2. Reading Text Files — Open a text file and read its contents safely.
  • 3. Writing Text Files — Create or replace text files with clear output.

1. Paths and Working Directories

Find files reliably using paths and the current working directory.

TipAnalogy

A path is an address, and the working directory is your current neighborhood.

What this means

A path describes where a file lives; the working directory is the folder Python starts searching from.

Example 1

Predict what will happen before you run the code.

from pathlib import Path
print(Path.cwd())
data_file = Path("data") / "scores.csv"
print(data_file)

Step-by-step explanation

  1. from pathlib import Path — pause here and say what this line reads, creates, changes, or displays.
  2. print(Path.cwd()) — pause here and say what this line reads, creates, changes, or displays.
  3. data_file = Path("data") / "scores.csv" — pause here and say what this line reads, creates, changes, or displays.
  4. print(data_file) — pause here and say what this line reads, creates, changes, or displays.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

A file can exist but still not be found if your program starts in a different working directory.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

2. Reading Text Files

Open a text file and read its contents safely.

TipAnalogy

Reading a file is like opening a notebook and copying a paragraph onto your desk.

What this means

Reading a file copies text from storage into your program.

Example 2

Predict what will happen before you run the code.

from pathlib import Path
text = Path("notes.txt").read_text(encoding="utf-8")
print(text)

Step-by-step explanation

  1. from pathlib import Path — pause here and say what this line reads, creates, changes, or displays.
  2. text = Path("notes.txt").read_text(encoding="utf-8") — pause here and say what this line reads, creates, changes, or displays.
  3. print(text) — pause here and say what this line reads, creates, changes, or displays.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

Encoding problems are easier to debug when you specify encoding=“utf-8” consistently.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

3. Writing Text Files

Create or replace text files with clear output.

TipAnalogy

Writing a file is like saving a note in a folder for future you.

What this means

Writing sends text from your program to storage.

Example 3

Predict what will happen before you run the code.

from pathlib import Path
report = "Result: success\n"
Path("report.txt").write_text(report, encoding="utf-8")

Step-by-step explanation

  1. from pathlib import Path — pause here and say what this line reads, creates, changes, or displays.
  2. report = "Result: success\n" — pause here and say what this line reads, creates, changes, or displays.
  3. Path("report.txt").write_text(report, encoding="utf-8") — pause here and say what this line reads, creates, changes, or displays.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

write_text replaces existing content. If that is risky, write to a new file name first.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

Notebook and Colab practice

Open a blank notebook at https://colab.new. Use one section at a time: copy the Example 1, predict the result, run it, answer the section quiz, and then move to the next section. This is better than copying the entire page at once.

Instructor note

Teaching notes
  • Treat each section as a short teaching episode.
  • Pause for the section quiz before introducing the next section.
  • Ask learners to compare sections: what stayed the same, and what changed?
  • If time is short, teach the first two sections live and assign the rest as practice.

Key points

TipKey points
  • Paths and Working Directories: A path describes where a file lives; the working directory is the folder Python starts searching from.
  • Reading Text Files: Reading a file copies text from storage into your program.
  • Writing Text Files: Writing sends text from your program to storage.
  • Use the section quizzes as gates: review before moving on if a quiz feels uncertain.

References

  • pathlib documentation: https://docs.python.org/3/library/pathlib.html
  • csv documentation: https://docs.python.org/3/library/csv.html
  • json documentation: https://docs.python.org/3/library/json.html
  • Python Tutorial: https://docs.python.org/3/tutorial/
  • Quarto OJS documentation: https://quarto.org/docs/interactive/ojs/
  • ipywidgets documentation: https://ipywidgets.readthedocs.io/en/stable/
Back to top