PYTHON • INPUT AND OUTPUT

File Paths — Handle basic file path issues (relative vs absolute) (conceptual)

Learn how your Python programs find and open files by understanding the addressing system every operating system uses.

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
The UNIX operating system introduced the idea of organizing files in a tree of nested directories, using the forward slash / as a separator. This structure became the standard for Linux and macOS.
1981
MS-DOS Adopts Backslash Paths
Microsoft's MS-DOS used drive letters and a backslash \ 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
Guido van Rossum released Python, which included the os module to handle file paths across different operating systems, shielding programmers from platform differences.
2014
Python 3.4 Introduces pathlib
The 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.

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.

1

Absolute Path

A complete address starting from the root of the file system. On Windows this begins with a drive letter like C:\; on macOS/Linux it starts with /. It works no matter what directory your program is currently in.
2

Relative Path

A partial address that starts from the current working directory (CWD)—the folder where your program is running. For example, data/scores.csv means "look in a 'data' folder inside the current directory."
3

Current Working Directory (CWD)

The folder from which your Python script is being executed. Python's os.getcwd() tells you this location. All relative paths are resolved starting here.
4

Path Separator

The character used to separate folder names. Windows uses a backslash \ while macOS and Linux use a forward slash /. Python's os.sep gives you the correct one automatically.
5

The Parent Directory Shortcut (..)

Two dots .. 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
Think of an absolute path like a full GPS address ("1600 Pennsylvania Ave NW, Washington, DC 20500")—it works from anywhere in the world. A relative path is like saying "go two blocks north, then turn left"—it only works if you already know where you're starting from.

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.

This directory tree shows a macOS/Linux file system. The root is at the top. The purple folder 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.

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.

This flowchart shows how the operating system decides whether a path is absolute or relative and then resolves it to a final file location. Both approaches ultimately produce a full path—or raise a FileNotFoundError if any step in the chain is wrong.

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.

Key differences in file path conventions between Windows and macOS/Linux
FeatureWindowsmacOS / Linux
RootDrive letter, e.g. C:\Single slash /
SeparatorBackslash \Forward slash /
Case sensitive?No — File.txt = file.txtYes — File.txt ≠ file.txt
Example absolute pathC:\Users\alex\project\data.csv/Users/alex/project/data.csv
Home directoryC:\Users\alex/home/alex (Linux) or /Users/alex (Mac)

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
In Python, the backslash \ 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.

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 DirectoryWhen you run python app.py from inside my_project/, Python sets the CWD to /Users/alex/my_project. You can verify this by running import os; print(os.getcwd()).
CWD = /Users/alex/my_project
2
Step 2 — Determine the Relationship Between CWD and the Target FileThe file scores.csv is located inside a subfolder called data/ 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 use os.path.join('data', 'scores.csv'). On macOS this produces data/scores.csv; on Windows it would produce data\scores.csv. Both are correct for their platform.
Cross-platform path: os.path.join('data', 'scores.csv')
4
Step 4 — Open the FileNow we can open the file safely. The full code looks like this: import os, then filepath = os.path.join('data', 'scores.csv'), then with 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 pathlibThe modern approach uses from pathlib import Path, then filepath = 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'

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.

Trade-offs between absolute and relative file paths
CriterionAbsolute PathRelative Path
PortabilityBreaks if the project moves to a different computer or folderWorks as long as the project's internal structure stays the same
ReliabilityAlways resolves to the same location, regardless of CWDCan break if the script is run from an unexpected directory
ReadabilityLonger and more cluttered, especially on WindowsShorter, cleaner, easier to type
CollaborationFails for teammates with different usernames or OSWorks for all teammates who clone the same project
Best use caseSystem-wide files like config files or installed librariesFiles inside your own project folder
✦ KEY TAKEAWAY
For most school and personal projects, relative paths are the better choice because they make your code portable—you can zip up the project, send it to a friend, and it will still work. Use absolute paths only when you need to reference a file that lives outside your project, like a system log or an installed program.

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.

How today's concepts connect to more advanced Python file handling
Concept You KnowAdvanced Extension
Using os.path.join() to build pathsUsing pathlib.Path objects with methods like .exists(), .is_dir(), and .glob()
Opening a single file with a relative pathRecursively walking entire directory trees with os.walk() or Path.rglob()
Knowing the CWD mattersUsing __file__ to make paths relative to the script's location instead of the CWD
Handling paths on your own computerWorking with file paths on remote servers, cloud storage, or URLs (which follow similar hierarchical patterns)

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.

Practice Problems

Test your understanding of file paths with these five problems. Each one builds on the previous concepts, increasing in complexity.

PROBLEM 1 — CONCEPTUAL
What is the main difference between an absolute path and a relative path? Give one advantage of each.
PROBLEM 2 — BASIC CALCULATION
Your current working directory is /Users/alex/my_project. What absolute path does the relative path data/scores.csv resolve to? What about ../Desktop/notes.txt?
PROBLEM 3 — INTERMEDIATE
A student writes this Python code on Windows: 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.
PROBLEM 4 — APPLIED
You're collaborating on a project with a friend using GitHub. Your project has this structure: 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?
PROBLEM 5 — CRITICAL THINKING
A Python script at /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.

Lesson 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.

Varsity Tutors • Python • File Paths — Handle basic file path issues (relative vs absolute) (conceptual)