Skip to content

Module 13 · File Handling — topic 12 of 15

File paths

Absolute and relative paths, the current working directory, building paths portably with os.path and pathlib, extracting names and extensions, and checking whether paths exist.

Beginner 8 min read·Lesson 205 of 306 in Python Programming

Learning objectives

  • Distinguish absolute and relative paths
  • Build paths that work on every operating system
  • Extract file names, stems and extensions

Definition

A file path tells the operating system where a file is. An absolute path starts at the root of the file system; a relative path is interpreted from the current working directory. Python's os.path and pathlib modules build and inspect paths portably.

Introduction

'File not found' is often a path problem: the file is there, but the program looks in a different folder. Understanding paths fixes that.

Why it matters

Windows uses backslashes and drive letters; macOS and Linux use forward slashes. Building paths with Python's tools keeps programs portable.

Detailed explanation

Absolute paths are complete: C:\Users\Asha\notes.txt on Windows, /home/asha/notes.txt on Linux.

Relative paths such as data/notes.txt are resolved from the current working directory (os.getcwd()), which depends on where the program was started.

Don't build paths by hand with "/" or "\\". Use os.path.join("data", "notes.txt") or pathlib's / operator, which use the correct separator.

os.path.basename, dirname and splitext extract parts of a path; os.path.abspath converts a relative path to an absolute one.

os.path.exists, isfile and isdir check what is at a path.

To find files next to your script regardless of the working directory, build paths from the script's own location: Path(__file__).parent / "data.txt".

pathlib (covered later in this module) is the modern object-oriented way to handle paths; PurePosixPath and PureWindowsPath let you manipulate paths for other systems.

Syntax

Python
import os
path = os.path.join("data", "2026", "report.csv")
print(os.path.basename(path)) # report.csv
print(os.path.splitext(path)[1]) # .csv
print(os.path.exists(path))
  • join builds portable paths.
  • basename/dirname/splitext inspect them.
  • exists/isfile/isdir check them.

Code examples

Building and splitting paths

Python
import os
p = os.path.join("data", "2026", "report.csv")
print(os.path.basename(p), os.path.dirname(p) == os.path.join("data", "2026"))
print(os.path.splitext("report.final.csv"))
Output
report.csv True
('report.final', '.csv')

Relative, absolute and existence checks

Python
import os
print(os.path.isabs("notes.txt"), os.path.isabs(os.path.abspath("notes.txt")))
print(os.path.exists("notes.txt"))
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("x")
print(os.path.exists("notes.txt"), os.path.isfile("notes.txt"), os.path.isdir("."))
Output
False True
False
True True True

More examples

Paths for other operating systems

Python
from pathlib import PurePosixPath, PureWindowsPath
p = PurePosixPath("/home/asha/projects/app/main.py")
print(p.name, p.stem, p.suffix, p.parent.name)
print(p.relative_to("/home/asha"))
w = PureWindowsPath(r"C:\Users\Asha\Documents\notes.txt")
print(w.drive, w.name, w.parts[1:3])
print(PurePosixPath("data") / "raw" / "file.csv")
Output
main.py main .py app
projects/app/main.py
C: notes.txt ('Users', 'Asha')
data/raw/file.csv

Step-by-step explanation

  • Pure paths only manipulate text; they never touch the disk, so they work for any operating system.
  • name, stem and suffix split the file name; parent moves up one level.
  • The / operator joins path parts with the right separator.

Expected output

Running “Paths for other operating systems” prints exactly:

TextOutput
main.py main .py app
projects/app/main.py
C: notes.txt ('Users', 'Asha')
data/raw/file.csv

Practical applications

  • Loading data files that sit next to a script.
  • Tools that process paths received from users on different systems.

Best practices

  • Build paths with os.path.join or pathlib.
  • Use paths relative to the script for bundled files.
  • Use raw strings for literal Windows paths.

Common mistakes

Hard-coded separators

Avoid

path = "data\\" + name

Prefer

path = os.path.join("data", name)

Backslashes only work on Windows (and are escape characters in strings).

Assuming the working directory

Avoid

open("config.json") # depends on where you run from

Prefer

open(Path(__file__).parent / "config.json", encoding="utf-8")

Running from a different folder breaks relative paths.

Important notes

  • os.path.expanduser("~") gives the user's home directory.

Key takeaways

  • Absolute paths are complete; relative ones depend on the working directory.
  • Build paths with join or /.
  • basename, dirname and splitext inspect paths.

Try it yourself

  1. 1
    Print the name, extension and parent folder of every path in a list.
  2. 2
    Write a function that returns a path to a file next to the running script.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “File Handling” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhich mode creates a new file but fails if the file already exists?
Practise this module