Files, folders and paths
Why this 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.
- 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?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.