Technology Files and Paths | Python Tutorial

Learn with diagrams, code, systems and practical examples.

</>
TutorialsPythonFiles and Paths
Functions & Modules · Chapter 18

Files and Paths

Read and write files safely with clear resource handling.

Why this matters

Scripts often need configuration, logs, generated output, CSV data, or local documents.

Start with the idea

Use with open(...) to make file lifetime explicit. pathlib gives an object-oriented way to work with filesystem paths across platforms.

IdeaUnderstand the purpose
CodeRun the smallest example
PracticeChange it yourself
SubjectVision learning pattern: understand the idea before memorizing syntax.

Small working example

Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.

Python
from pathlib import Path

path = Path("notes.txt")
path.write_text("hello", encoding="utf-8")
print(path.read_text(encoding="utf-8"))
Expected output
hello
What to notice

The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.

Common beginner mistake

Mistake

Assuming the current working directory is always the directory where the script lives.

Better approach

Be explicit about path roots when location matters, especially in automation and deployment environments.

Quick recap

  • Files are external resources.
  • Use explicit encodings.
  • Paths should be handled deliberately.

Try it yourself

These are deliberately small. If you can complete them without copying the example, you are ready to continue.

  1. Write three lines to a file.
  2. Read them back and count the lines.