Index Ai Academy
Phase 0 · Working with data

Files, folders and paths

What a file's name tells you, paths as directions through folders, and where a relative path starts.

About 30 minutes · Free lesson

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
Quick check
A guess before you start. A program is told to open 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?
  1. A program can't open a table; only a spreadsheet app can do that
  2. The file is too big for Python to open in one go
  3. The file's name needs capital letters before Python can see it
  4. The program started in a different folder from the one you had in mind
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:

ExtensionWhat's inside
.txtplain text
.csva table, saved as plain text with commas between the columns
.pyPython code
.jsonstructured data, in a text format programs share
.png, .jpga picture

Three things about names catch people out.

  • The extension is only a label. Renaming photo.png to photo.txt doesn'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 sales when the real name is sales.csv. Both have a setting to show extensions. Turn it on.
  • Capitals may or may not count. On most servers, Sales.csv and sales.csv are 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.
Quick check
Which of these names has the extension csv?
  1. sales csv
  2. csv.sales
  3. sales_csv
  4. sales.2026.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"))
It runs right here in your browser, with nothing to install.

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.

Quick check
The extension is whatever follows the last dot. What does this print?
name = "holiday.photo.JPG"
print(name.split(".")[-1])
  1. holiday
  2. jpg
  3. photo
  4. JPG
Show the answer

JPG

Splitting on the dot gives three pieces, and [-1] takes the last: JPG, with its capitals as typed.

Quick check
You rename logo.png to logo.txt. What has changed?
  1. Nothing at all, because a name can't be changed once set
  2. Only the label: the data inside is still a picture
  3. The picture has been converted into readable text
  4. The file is now empty, because text can't hold a picture
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.

In your own words
What does a file's extension tell you, and why can't you fully trust it?

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.txt
  • projects/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.

Try it now
In your own words
Two files have the same name. How can a computer keep both, and how do you say which one you mean?

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.txt and notes.txt are the same file.
  • .. means "one folder up". From projects/shop/data, the path ../notes.txt climbs to projects/shop and finds its notes. ../../blog/notes.txt climbs twice, to projects, and then walks down into blog.
Quick check
Using the tree from earlier: a program's working folder is projects/shop. Which path opens the stock table?
  1. data/stock.csv
  2. ../data/stock.csv
  3. stock.csv
  4. /data/stock.csv
Show the answer

data/stock.csv

From projects/shop, the data folder is one step down, and stock.csv is inside it.

Quick check
The working folder is projects/shop/data. Where does ../../blog/notes.txt lead?
  1. blog/notes.txt
  2. projects/shop/blog/notes.txt
  3. projects/shop/data/blog/notes.txt
  4. projects/blog/notes.txt
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.

In your own words
Why can the same relative path find a file on one run and miss it on the next?

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.

Quick check
Everything except the last step is the folder. What does this print?
path = "blog/2026/draft.txt"
steps = path.split("/")
print("/".join(steps[:-1]))
  1. ['blog', '2026']
  2. blog/2026/draft.txt
  3. draft.txt
  4. blog/2026
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.

Drill

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)
In the lesson, your code is checked as you write it.
Worked example

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))
In the lesson you can change this and run it.

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.

Drill

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)
In the lesson, your code is checked as you write it.

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.

In your own words
Why build a path from parts, with an f-string or the / operator, instead of typing it out in full each time?

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:

  1. Spelling and capitals. Sales.csv is not sales.csv on a server. Compare the name letter by letter.
  2. The hidden extension. The file you see as sales may be sales.csv, or sales.csv.txt.
  3. The working folder. A relative path starts there. Ask where the program is running, not where the file is.
  4. The slashes. Forward slashes, with no slash at the front unless you mean the top of the disk.
  5. Spaces. my report.csv is a legal name and a steady source of trouble. Prefer my-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.

Quick check
A folder of photos has names ending in .jpg, .JPG and .Jpg. From the Strings lesson: what does this print?
name = "IMG_0412.JPG"
print(name.endswith(".jpg"), name.lower().endswith(".jpg"))
  1. True False
  2. False False
  3. True True
  4. False True
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.

In your own words
A program reports that a file isn't found, and you can see the file. What do you check?

Write a sentence or two, then compare it with a good answer in the lesson.

Goes deeper in

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?

  1. /Users/ana/projects/notes.txt
  2. projects/notes.txt
  3. ../notes.txt
  4. ./projects/notes.txt

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

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
  1. Your first program FreeRun Python, print output, and read an error message without panicking.24 min
  2. Typing code exactly FreeBrackets, quotes, indentation and the look-alike characters that stop a program.26 min
  3. Variables FreeGive values names so your program can remember and reuse them.24 min
  4. Numbers and arithmetic FreeIntegers, decimals, rounding, and the math behind every metric.30 min
  5. Strings and f-strings FreeWork with text: join it, slice it, clean it, and format it.30 min
  6. Decisions with if/else FreeCompare values and choose what happens next.35 min
  7. Fractions, ratios and rates FreeShares, rates, percentage points and ratios, with Python doing the arithmetic.35 min
  8. 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
  9. Lists FreeKeep many values in order, then index, slice and change them.28 min
  10. Files, folders and paths FreeWhat a file's name tells you, paths as directions through folders, and where a relative path starts.30 min
  11. Loops FreeRepeat work over every item without copy-pasting code.35 min
  12. 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
  13. 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
  14. Dictionaries FreeLook values up by name: the shape of almost all real-world data.40 min
  15. Functions FreePackage steps into reusable, testable pieces with inputs and outputs.35 min
  16. While loops FreeRepeat until something changes: goals reached, answers valid, tasks done.38 min
  17. Functions as values FreeStore functions, pass them in with key=, and accept any number of arguments.40 min
  18. Comprehensions FreeFilter and transform a whole collection in one readable line.38 min
  19. Errors and exceptions FreeRead tracebacks, and handle the failures you expect.38 min
  20. Finding bugs when nothing crashes FreeA method for wrong answers: expected against actual, reproduce, look inside, fix one thing.36 min
  21. Sets: unique items and fast lookups FreeDuplicates, fast membership, set operations and comparing two lists.34 min
  22. Modules and imports FreeUse Python's standard library instead of reinventing it.38 min
  23. Classes and objects FreeBundle data with the functions that work on it.38 min
  24. Inheritance and class attributes FreeBuild classes on other classes, and share values across every object.35 min
  25. 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
  26. JSON FreeThe text format APIs and LLMs use to exchange structured data.34 min
  27. Files and CSV data FreeRead and write files, and turn a spreadsheet export into Python data.33 min
  28. NumPy arrays FreeDo math on whole columns at once, the foundation of every ML library.30 min
  29. 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
  30. DataFrames with pandas FreeLoad a table, pick rows and columns, and summarize groups in a few lines.40 min
  31. Charts with Matplotlib FreeLine, bar, scatter, histogram and box plots, labeled and honest.42 min
  32. Project: images are arrays FreeGray, crop, brighten, watermark and palette tools built on NumPy and Pillow.45 min
  33. The terminal FreeNavigate folders and run programs by typing commands.30 min
  34. Version control with git FreeSave snapshots of your work, undo mistakes, and share code.30 min
  35. Packages and environments FreeInstall libraries with pip and keep projects isolated with venv.25 min
  36. Python on your own computer FreeInstall Python and VS Code, make a virtual environment, then run, debug and test a project.45 min
  37. How APIs work FreeRequests, responses, methods, status codes and headers.30 min
  38. Calling APIs from Python FreeSend requests, read JSON responses, and handle failures.35 min
  39. API keys and secrets FreeAuthenticate safely and keep keys out of your code.25 min
  40. Your first LLM call FreeSend messages to a model and read its reply, tokens and stop reason.30 min
  41. Capstone: ad-copy reviewer FreeCombine files, functions, JSON and an LLM call into one small tool.40 min
  42. Dates, times and time zones Freedatetime, timedelta, formats, time zones and the traps when clocks change.42 min
  43. Regular expressions FreeFind, check, extract and clean text patterns with the re module.42 min
  44. Sending email and text messages FreeEmailMessage, smtplib, mail merge and an SMS API, with secrets kept out of code.42 min
  45. Web pages: HTML and CSS FreeRead and write HTML, what forms send, CSS selectors and escaping.42 min
  46. 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