Files, folders and paths
What a file's name tells you, paths as directions through folders, and where a relative path starts.
What it covers6
Why it matters
Every program you write from here on reads or writes files: a table of sales, a list of prompts, a model's saved weights, a log of what went wrong. The most common error outside this browser is "no such file", and the file is nearly always there. The directions to it were wrong. A path is those directions, and this lesson teaches you to read one, write one, and work out where it leads.
What you'll be able to do
- Say what a file's name and extension tell you, and what they don't
- Read a path as directions through folders to one file
- Tell an absolute path from a relative one, and use . and .. in a relative path
- Take a path apart and build one in Python with split, join and slices, and with pathlib's Path
- Explain why a notebook raises FileNotFoundError for data/train.jsonl, and fix it
data/sales.csv and reports that there's no such file. You can see the file on your computer. What is the most likely reason?Show the answer
The program started in a different folder from the one you had in mind
data/sales.csv means "from where I am now, go into data and find sales.csv". If the program starts somewhere else, the same words point at a place where no such file exists. This lesson is about that "from where I am now".
The idea: a path is directions through folders
Start with what a file is and what its name tells you.
A file and its name
A file is a named piece of stored data: a photo, a letter, a table, a program. Its name usually has two parts with a dot between them. In sales.csv, the part before the dot is the name you chose, and the part after the last dot is the extension.
The extension is a label for what kind of thing is inside. A few you'll meet in this course:
| Extension | What's inside |
|---|---|
.txt | plain text |
.csv | a table, saved as plain text with commas between the columns |
.py | Python code |
.json | structured data, in a text format programs share |
.png, .jpg | a picture |
Three things about names catch people out.
- The extension is only a label. Renaming
photo.pngtophoto.txtdoesn't turn the picture into text. It changes the label, and apps then guess wrong about what's inside. - Your computer may hide it. Windows and macOS often show
saleswhen the real name issales.csv. Both have a setting to show extensions. Turn it on. - Capitals may or may not count. On most servers,
Sales.csvandsales.csvare two different files. On most laptops they're the same one. Type names as they are, every time, and your code works in both places.
csv?Show the answer
sales.2026.csv
The extension is what follows the last dot. Only sales.2026.csv ends with .csv.
A name is a string, so the string tools you know can take it apart:
name = "report.final.pdf" pieces = name.split(".") print(pieces) print("extension:", pieces[-1]) print("is it a PDF?", name.endswith(".pdf"))
The name has two dots, so splitting gives three pieces. The extension is the last one, which is why [-1] is the safe way to reach it.
name = "holiday.photo.JPG" print(name.split(".")[-1])
Show the answer
JPG
Splitting on the dot gives three pieces, and [-1] takes the last: JPG, with its capitals as typed.
logo.png to logo.txt. What has changed?Show the answer
Only the label: the data inside is still a picture
An extension is a label, and renaming changes nothing inside the file. A text editor that trusts the new label will open it and show nonsense.
Write a sentence or two, then compare it with a good answer in the lesson.
Folders inside folders
A folder holds files and other folders. Programmers also call it a directory. Folders inside folders make a shape like a family tree, drawn here with each level pushed further right:
projects
├── shop
│ ├── data
│ │ ├── sales.csv
│ │ └── stock.csv
│ ├── report.py
│ └── notes.txt
└── blog
└── notes.txt
There are two files called notes.txt here, and that's fine, because they live in different folders. What tells them apart is the path: the folders you walk through, in order, and then the file's name, with a slash between each step.
projects/shop/notes.txtprojects/blog/notes.txt
Read a path left to right as directions: "go into projects, then into shop, and there you'll find notes.txt".
Windows writes its paths with a backslash, as in projects\shop\notes.txt. macOS, Linux and the web use the forward slash. Python accepts the forward slash on every system, so that's the one to type.
Write a sentence or two, then compare it with a good answer in the lesson.
Where the directions start
Directions need a starting point. "Second door on the left" only helps if you know which corridor you're in. Paths have the same problem, and two answers to it.
An absolute path starts from the very top of the disk, so it works from anywhere. On macOS and Linux it begins with a slash: /Users/ana/projects/shop/notes.txt. On Windows it begins with a drive letter: C:\Users\ana\projects\shop\notes.txt.
A relative path starts from wherever the program is now. That place is called the working folder. data/sales.csv means "from the working folder, go into data, and find sales.csv". It's short, and it keeps working when the whole project moves to another computer. Its weakness is that it means something different from every starting point. If the working folder is projects/shop, it finds the file. If the working folder is projects, the same words lead nowhere.
Two special steps help a relative path move around:
.means "here, the working folder"../notes.txtandnotes.txtare the same file...means "one folder up". Fromprojects/shop/data, the path../notes.txtclimbs toprojects/shopand finds its notes.../../blog/notes.txtclimbs twice, toprojects, and then walks down into blog.
projects/shop. Which path opens the stock table?Show the answer
data/stock.csv
From projects/shop, the data folder is one step down, and stock.csv is inside it.
projects/shop/data. Where does ../../blog/notes.txt lead?Show the answer
projects/blog/notes.txt
Two .. steps climb from data to shop to projects. Then the path walks down into blog and finds notes.txt.
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: take a path apart and build one
Purpose. A path is a string, so the string and list tools you know can read it and build it.
Splitting it on the slash gives the steps as a list, and the list tools from the last lesson do the rest:
path = "projects/shop/data/sales.csv" steps = path.split("/") print(steps) print("file:", steps[-1]) print("folder:", "/".join(steps[:-1])) print("folders to walk through:", len(steps) - 1)
steps[:-1] is every step except the last, which is the folder the file sits in. "/".join(...) glues those steps back together with slashes.
path = "blog/2026/draft.txt" steps = path.split("/") print("/".join(steps[:-1]))
Show the answer
blog/2026
steps[:-1] keeps blog and 2026 and drops the file's name. Joining them with a slash gives blog/2026, the folder the draft is in.
Take a path apart
A photo sits at the path below. Set filename to the file's name, extension to what follows its last dot, and folder to the path of the folder it's in. Work them out from path, so the code still works if the path changes.
path = "photos/2026/summer/beach.jpg" filename = "" # the last step of the path extension = "" # what follows the last dot of the file's name folder = "" # every step except the last, joined with slashes print(filename, extension, folder)
Worked example: where does ../notes.txt lead?
A program's working folder is projects/shop/data, and it's asked for ../notes.txt. Work out the full path by hand: each .. removes one step from the end of the working folder, and the rest of the relative path is added on.
here = "projects/shop/data" relative = "../notes.txt" here_steps = here.split("/") rel_steps = relative.split("/") ups = rel_steps.count("..") kept = here_steps[:len(here_steps) - ups] target = kept + rel_steps[ups:] print("climb", ups, "folder, then:", "/".join(target))
One .., so one step comes off the end of the working folder, leaving projects/shop. The rest of the relative path, notes.txt, is added on: projects/shop/notes.txt. Change relative to ../../blog/notes.txt and run it again: two steps come off, and the path walks down into blog.
Build the path
A report is saved once a month, in a folder for its year and month. From the four values below, build path so it is exports/2026/03/sales.csv, and backup so it is exports/2026/03/sales-backup.csv. Use the variables, so next month's path needs only month changed.
top = "exports" year = 2026 month = "03" name = "sales" path = "" # exports/2026/03/sales.csv backup = "" # exports/2026/03/sales-backup.csv print(path) print(backup)
Path objects. The standard library's pathlib does the same taking-apart with names instead of slices, and it joins with /, so you never type a slash by hand. Plain split is how it works inside; Path is what real code uses.
from pathlib import Path p = Path("projects/shop/data/sales.csv") print(p.name, p.stem, p.suffix, p.parent) print(Path("exports") / "2026" / "03" / "sales.csv")
name is the last step, stem is the name without its extension, suffix is the extension with its dot, and parent is the folder. The / operator glues steps together the way "/".join did.
Write a sentence or two, then compare it with a good answer in the lesson.
In AI work: checkpoints, datasets and a missing file
Purpose. Training and evaluation code is full of paths, and "file not found" is its most common first error.
An engineer's week has them everywhere: a run writes checkpoints/epoch_3.pt after each pass over the data, an evaluation reads data/train.jsonl, and a config names outputs/run-7. Building the name from the epoch number means every checkpoint gets its own file.
Why a notebook says FileNotFoundError. A relative path starts from the working folder. A notebook's working folder is wherever the notebook was opened, which is often not the project's top folder. The same data/train.jsonl then points at a place that has no such file. The cell below asks for it from a folder that doesn't hold it and reads the error's own details:
from pathlib import Path try: open("data/train.jsonl") except FileNotFoundError as err: print(type(err).__name__, err.filename) print(Path("data/train.jsonl").exists())
exists() answers True or False without raising, so a script can check before it reads. The fix is rarely to move the file: open the notebook from the project's top folder, or build the path from a known starting point.
When the file isn't found
When a program can't find a file, it says so: Python's report ends with FileNotFoundError and the path it tried. The file is almost never gone. Work down this list, in this order:
- Spelling and capitals.
Sales.csvis notsales.csvon a server. Compare the name letter by letter. - The hidden extension. The file you see as
salesmay besales.csv, orsales.csv.txt. - The working folder. A relative path starts there. Ask where the program is running, not where the file is.
- The slashes. Forward slashes, with no slash at the front unless you mean the top of the disk.
- Spaces.
my report.csvis a legal name and a steady source of trouble. Prefermy-report.csv.
String tools can do some of this checking for you. Lowercasing a name before you test its extension makes the test work whatever capitals the file came with.
name = "IMG_0412.JPG" print(name.endswith(".jpg"), name.lower().endswith(".jpg"))
Show the answer
False True
endswith compares characters exactly, and J-P-G isn't j-p-g. .lower() first makes the name img_0412.jpg, which does end with .jpg.
Write a sentence or two, then compare it with a good answer in the lesson.
Goes deeper in
- The terminal:
cd,lsand the working folder, live. - Files and CSV data: opening, reading and writing the files a path leads to.
Practice what you just read
- 5 code examples you can edit and run
- a practice exercise that checks your code
- a 5-question quiz
- 10 review cards for spaced repetition
Try a quiz question
Which of these is an absolute path?
Before this lesson
Where this lesson leads.
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Phase 0 · about 32 hours of study
Tools
Python, the terminal and calling APIs
46 lessons All free
- Your first program FreeRun Python, print output, and read an error message without panicking.24 min
- Typing code exactly FreeBrackets, quotes, indentation and the look-alike characters that stop a program.26 min
- Variables FreeGive values names so your program can remember and reuse them.24 min
- Numbers and arithmetic FreeIntegers, decimals, rounding, and the math behind every metric.30 min
- Strings and f-strings FreeWork with text: join it, slice it, clean it, and format it.30 min
- Decisions with if/else FreeCompare values and choose what happens next.35 min
- Fractions, ratios and rates FreeShares, rates, percentage points and ratios, with Python doing the arithmetic.35 min
- Ranges and edges in code FreeAt least, under and between as symbols; intervals with each end in or out; bands with no gaps.32 min
- Lists FreeKeep many values in order, then index, slice and change them.28 min
- Files, folders and paths FreeWhat a file's name tells you, paths as directions through folders, and where a relative path starts.30 min
- Loops FreeRepeat work over every item without copy-pasting code.35 min
- Formulas: order, powers and rearranging FreeWork a calculation in the right order, fill in a formula, and turn it around to find what's missing.24 min
- Loops that add and count: sequences, sums and combinations FreeSequences that add or multiply each step, a formula for any term, and adding a sequence up.34 min
- Dictionaries FreeLook values up by name: the shape of almost all real-world data.40 min
- Functions FreePackage steps into reusable, testable pieces with inputs and outputs.35 min
- While loops FreeRepeat until something changes: goals reached, answers valid, tasks done.38 min
- Functions as values FreeStore functions, pass them in with key=, and accept any number of arguments.40 min
- Comprehensions FreeFilter and transform a whole collection in one readable line.38 min
- Errors and exceptions FreeRead tracebacks, and handle the failures you expect.38 min
- Finding bugs when nothing crashes FreeA method for wrong answers: expected against actual, reproduce, look inside, fix one thing.36 min
- Sets: unique items and fast lookups FreeDuplicates, fast membership, set operations and comparing two lists.34 min
- Modules and imports FreeUse Python's standard library instead of reinventing it.38 min
- Classes and objects FreeBundle data with the functions that work on it.38 min
- Inheritance and class attributes FreeBuild classes on other classes, and share values across every object.35 min
- Review: find the slip (Python core) FreeTen slips that run without an error, found by working a tiny input by hand, and the construct sheet for NumPy and PyTorch code.30 min
- JSON FreeThe text format APIs and LLMs use to exchange structured data.34 min
- Files and CSV data FreeRead and write files, and turn a spreadsheet export into Python data.33 min
- NumPy arrays FreeDo math on whole columns at once, the foundation of every ML library.30 min
- NumPy in practice: shapes, types and picking values FreeReshape, view and copy, where and clip, top-k, stacking and the (N, C, H, W) batch a model expects.35 min
- DataFrames with pandas FreeLoad a table, pick rows and columns, and summarize groups in a few lines.40 min
- Charts with Matplotlib FreeLine, bar, scatter, histogram and box plots, labeled and honest.42 min
- Project: images are arrays FreeGray, crop, brighten, watermark and palette tools built on NumPy and Pillow.45 min
- The terminal FreeNavigate folders and run programs by typing commands.30 min
- Version control with git FreeSave snapshots of your work, undo mistakes, and share code.30 min
- Packages and environments FreeInstall libraries with pip and keep projects isolated with venv.25 min
- Python on your own computer FreeInstall Python and VS Code, make a virtual environment, then run, debug and test a project.45 min
- How APIs work FreeRequests, responses, methods, status codes and headers.30 min
- Calling APIs from Python FreeSend requests, read JSON responses, and handle failures.35 min
- API keys and secrets FreeAuthenticate safely and keep keys out of your code.25 min
- Your first LLM call FreeSend messages to a model and read its reply, tokens and stop reason.30 min
- Capstone: ad-copy reviewer FreeCombine files, functions, JSON and an LLM call into one small tool.40 min
- Dates, times and time zones Freedatetime, timedelta, formats, time zones and the traps when clocks change.42 min
- Regular expressions FreeFind, check, extract and clean text patterns with the re module.42 min
- Sending email and text messages FreeEmailMessage, smtplib, mail merge and an SMS API, with secrets kept out of code.42 min
- Web pages: HTML and CSS FreeRead and write HTML, what forms send, CSS selectors and escaping.42 min
- Scraping web pages FreeBeautiful Soup, one record per item, pagination and robots.txt.45 min
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write