SECTION 1
Historical Context & Motivation
Before computers had graphical desktops with clickable folder icons, users interacted with files entirely through typed commands. Every time you wanted to open, move, or delete a file, you had to tell the computer exactly where that file lived using a text-based address called a file path. This concept is just as important today—especially in programming. When your Python script tries to open a file and you see a FileNotFoundError, the problem is almost always a path issue.
1969 • UNIX Introduces Hierarchical Directories
/ as a separator. This structure became the standard for Linux and macOS.1981 • MS-DOS Adopts Backslash Paths
\ as a separator, creating a different path convention—for example, C:\Users\file.txt. This difference still causes headaches for programmers today.1991 • Python Is Created
os module to handle file paths across different operating systems, shielding programmers from platform differences.2014 • Python 3.4 Introduces pathlib
pathlib module arrived in Python 3.4, offering a modern, object-oriented way to construct and manipulate file paths that works seamlessly on Windows, macOS, and Linux.The core question this lesson addresses is straightforward: How does a program know where a file is located, and why do path mistakes cause so many errors? Understanding the difference between relative and absolute paths will save you hours of frustrating debugging.
SECTION 2
Core Principles & Definitions
A file path is essentially a street address for a file on your computer. Just as a mailing address tells a delivery driver which house to visit, a file path tells your operating system—and your Python program—where to find a specific file. There are two fundamental types of paths, and grasping the distinction between them is the most important skill in this lesson.
Absolute Path
C:\; on macOS/Linux it starts with /. It works no matter what directory your program is currently in.Relative Path
data/scores.csv means "look in a 'data' folder inside the current directory."Current Working Directory (CWD)
os.getcwd() tells you this location. All relative paths are resolved starting here.Path Separator
\ while macOS and Linux use a forward slash /. Python's os.sep gives you the correct one automatically.The Parent Directory Shortcut (..)
.. mean "go up one level" in the directory tree. A single dot . means "the current directory." These shortcuts are used in relative paths to navigate around the file system.KEY TAKEAWAY
SECTION 3
Visual Explanation — The Directory Tree
A computer's file system is structured like an upside-down tree. The root sits at the top, and directories branch downward. The diagram below shows a simplified file system with a Python project inside it. Study it carefully—it will be referenced throughout the rest of this lesson.
my_project/ is our current working directory. Notice how the absolute path traces every folder from the root, while the relative path starts from my_project/.In the diagram, the absolute path to scores.csv spells out every single directory from the root: /Users/alex/my_project/data/scores.csv. The relative path is much shorter—data/scores.csv—because it assumes you're already inside my_project/. If you moved to the Desktop/ directory instead, that same relative path would fail because there's no data/ folder on the Desktop.
SECTION 4
How Path Resolution Works
When your Python program executes a line like open('data/scores.csv'), the operating system needs to convert that text string into an actual location on disk. This conversion process is called path resolution. The steps differ depending on whether the path is absolute or relative.
Absolute Path Resolution
The OS starts at the root of the file system and follows each directory name in sequence. For /Users/alex/my_project/data/scores.csv, the OS opens /, then Users, then alex, and so on until it reaches the file. Because the starting point is always the root, this resolution produces the same result regardless of where your script is located.
Relative Path Resolution
The OS starts at the current working directory (CWD) and appends the relative path to it. So if the CWD is /Users/alex/my_project and you open data/scores.csv, the OS combines them into /Users/alex/my_project/data/scores.csv. This means the result depends entirely on where you launched the script from.
The Role of .. and .
The double-dot symbol .. tells the OS to move up one level in the directory tree. For instance, from /Users/alex/my_project/data/, the path ../app.py resolves to /Users/alex/my_project/app.py. The single dot . simply means "this directory" and is often used for clarity—./data/scores.csv is the same as data/scores.csv.
FileNotFoundError if any step in the chain is wrong.SECTION 5
Cross-Platform Path Differences
One of the trickiest parts of working with file paths is that different operating systems use different conventions. If you write a path using Windows-style backslashes and then run your code on a Mac, it will break. Understanding these differences—and knowing how Python helps you avoid them—is essential.
| Feature | Windows | macOS / Linux |
|---|---|---|
| Root | Drive letter, e.g. C:\ | Single slash / |
| Separator | Backslash \ | Forward slash / |
| Case sensitive? | No — File.txt = file.txt | Yes — File.txt ≠ file.txt |
| Example absolute path | C:\Users\alex\project\data.csv | /Users/alex/project/data.csv |
| Home directory | C:\Users\alex | /home/alex (Linux) or /Users/alex (Mac) |
Key differences in file path conventions between Windows and macOS/Linux
Python's Cross-Platform Tools
Python gives you two great tools to write paths that work on any operating system. The os.path.join() function stitches folder names together using the correct separator for whatever OS the code runs on. Even better, the pathlib.Path class lets you use the / operator to combine path parts, and it automatically handles the conversion. For example, Path('data') / 'scores.csv' works correctly on both Windows and macOS.
Common Trap: Backslash in Python Strings
\ is also the escape character in strings. Writing "C:\new\test.txt" actually creates a string with a newline character \n and a tab character \t! Use raw strings r"C:\new\test.txt" or forward slashes instead. Better yet, use os.path.join() or pathlib.Path to avoid the problem entirely.SECTION 6
Worked Example — Opening a File Correctly
Suppose you have the project structure shown in Section 3. You're writing code in app.py and need to read scores.csv from the data/ folder. Let's walk through the process of building a correct path.
Reading scores.csv from app.py
- 1
Step 1 — Identify the Current Working Directory
When you runpython app.pyfrom insidemy_project/, Python sets the CWD to/Users/alex/my_project. You can verify this by runningimport os; print(os.getcwd()).CWD =/Users/alex/my_project - 2
Step 2 — Determine the Relationship Between CWD and the Target File
The filescores.csvis located inside a subfolder calleddata/which is directly inside the CWD. Since the file is "below" us in the tree, we navigate downward.Relative path =data/scores.csv - 3
Step 3 — Write the Python Code Using os.path.join()
Instead of hardcoding the path with slashes, we useos.path.join('data', 'scores.csv'). On macOS this producesdata/scores.csv; on Windows it would producedata\scores.csv. Both are correct for their platform.Cross-platform path:os.path.join('data', 'scores.csv') - 4
Step 4 — Open the File
Now we can open the file safely. The full code looks like this:import os, thenfilepath = os.path.join('data', 'scores.csv'), thenwith open(filepath, 'r') as f:. If the CWD is correct and the file exists, it will open successfully.File opens without error ✓ - 5
Step 5 — Alternative: Use pathlib
The modern approach usesfrom pathlib import Path, thenfilepath = Path('data') / 'scores.csv'. The/operator here is overloaded by pathlib—it builds a platform-correct path regardless of the operating system.pathlib equivalent:Path('data') / 'scores.csv'
SECTION 7
Absolute vs. Relative — Strengths & Limitations
Neither absolute nor relative paths are universally "better." Each has strengths that make it the right choice in certain situations and limitations that can cause bugs. The table below summarizes the trade-offs.
| Criterion | Absolute Path | Relative Path |
|---|---|---|
| Portability | Breaks if the project moves to a different computer or folder | Works as long as the project's internal structure stays the same |
| Reliability | Always resolves to the same location, regardless of CWD | Can break if the script is run from an unexpected directory |
| Readability | Longer and more cluttered, especially on Windows | Shorter, cleaner, easier to type |
| Collaboration | Fails for teammates with different usernames or OS | Works for all teammates who clone the same project |
| Best use case | System-wide files like config files or installed libraries | Files inside your own project folder |
Trade-offs between absolute and relative file paths
KEY TAKEAWAY
SECTION 8
Connection to Advanced Topics
Understanding file paths at a conceptual level prepares you for more advanced programming patterns. As your projects grow, you'll encounter scenarios where basic path knowledge isn't enough—but the principles stay the same.
| Concept You Know | Advanced Extension |
|---|---|
Using os.path.join() to build paths | Using pathlib.Path objects with methods like .exists(), .is_dir(), and .glob() |
| Opening a single file with a relative path | Recursively walking entire directory trees with os.walk() or Path.rglob() |
| Knowing the CWD matters | Using __file__ to make paths relative to the script's location instead of the CWD |
| Handling paths on your own computer | Working with file paths on remote servers, cloud storage, or URLs (which follow similar hierarchical patterns) |
How today's concepts connect to more advanced Python file handling
One particularly useful technique you'll learn next is using __file__ to anchor paths to the script's own location. This eliminates the CWD problem entirely because Path(__file__).parent / 'data' / 'scores.csv' always points to the data/ folder next to the script, regardless of where you launched it from. This pattern is extremely common in professional Python code.
SECTION 9
Practice Problems
Test your understanding of file paths with these five problems. Each one builds on the previous concepts, increasing in complexity.
Question 1: CONCEPTUAL
Show answer
/ on macOS/Linux or C:\ on Windows), while a relative path specifies the location starting from the current working directory. An advantage of absolute paths is that they always resolve to the same location, no matter where the script runs. An advantage of relative paths is portability—the project can be moved to a different computer or folder and still work, as long as the internal folder structure is preserved.Question 2: BASIC CALCULATION
/Users/alex/my_project. What absolute path does the relative path data/scores.csv resolve to? What about ../Desktop/notes.txt?Show answer
data/scores.csv resolves to /Users/alex/my_project/data/scores.csv because the OS appends the relative path to the CWD. For ../Desktop/notes.txt, the .. moves up one level to /Users/alex, and then descends into Desktop, giving a final absolute path of /Users/alex/Desktop/notes.txt.Question 3: INTERMEDIATE
open('C:\new_data\test.csv'). The file exists at C:\new_data\test.csv, but they get an error. Explain what's going wrong and provide two ways to fix it.Show answer
'C:\new_data\test.csv' is being interpreted as Python escape characters. Specifically, \n becomes a newline and \t becomes a tab, so Python is looking for a nonsensical path. Fix 1: use a raw string by adding r before the quote: open(r'C:\new_data\test.csv'). Fix 2: use forward slashes instead, which Python accepts on Windows: open('C:/new_data/test.csv'). A third option is using os.path.join('C:\\', 'new_data', 'test.csv').Question 4: APPLIED
project/main.py and project/assets/logo.png. You hardcode the path '/Users/alex/project/assets/logo.png' in main.py. Your friend clones the repo on their Windows machine. What goes wrong, and how would you rewrite the path so it works for both of you?Show answer
/Users/alex/project/assets/logo.png fails on your friend's computer for two reasons: (1) Windows uses drive letters instead of a / root, and your friend's username is different, and (2) the path separator is wrong for Windows. The fix is to use a relative path with a cross-platform tool: from pathlib import Path; filepath = Path('assets') / 'logo.png'. Since both you and your friend run the script from within the project/ folder, this relative path resolves correctly on both operating systems.Question 5: CRITICAL THINKING
/Users/alex/my_project/src/analysis.py opens '../data/results.csv'. It works perfectly when run as python src/analysis.py from my_project/, but fails when run as python analysis.py from inside src/. Explain why, and propose a solution that works regardless of where the script is launched.Show answer
my_project/, the CWD is /Users/alex/my_project and ../data/results.csv resolves to /Users/alex/data/results.csv—wait, that's not right either. Actually when run as python src/analysis.py from my_project/, the CWD is still my_project/, so ../data/results.csv resolves to /Users/alex/data/results.csv, which is wrong. But when run from inside src/, the CWD is /Users/alex/my_project/src and ../data/results.csv resolves to /Users/alex/my_project/data/results.csv—which is correct. So actually the first scenario fails and the second succeeds. The key insight is that relative paths depend on the CWD, not on where the script file lives. A robust solution uses Path(__file__).parent to anchor the path to the script's directory: filepath = Path(__file__).parent / '..' / 'data' / 'results.csv'. This always works because __file__ stores the actual location of the script, not the CWD.SUMMARY
Lesson Summary
Summary
A file path is the address a program uses to locate a file on your computer. An absolute path starts from the root of the file system and works from anywhere, while a relative path starts from the current working directory (CWD) and is shorter and more portable. The symbols . (current directory) and .. (parent directory) let you navigate up and down the directory tree within relative paths.
Windows uses backslash separators and drive letters, while macOS and Linux use forward slash separators. To write cross-platform Python code, use os.path.join() or pathlib.Path instead of hardcoding slashes. Most FileNotFoundError problems in Python come from path mistakes—wrong separator, wrong CWD, or using an absolute path that only works on one machine. When in doubt, use relative paths for files inside your project and keep your project structure organized.