File Paths

Build file paths with os.path.join() for cross-platform compatibility

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Relative vs absolute paths

A relative path describes a location relative to where your script runs.

open("data.txt")          # same folder as the script
open("data/sales.txt")    # data subfolder

An absolute path starts from the root of the file system.

open("/home/user/data/sales.txt")   # Linux/macOS
open("C:/Users/user/data/sales.txt")  # Windows

Building paths with os.path.join()

Different operating systems use different path separators: / on Linux and macOS, \ on Windows. os.path.join() builds paths using the correct separator for your system.

import os

path = os.path.join("data", "sales.txt")
print(path)  # data/sales.txt on Linux/macOS

Pass as many segments as you need — os.path.join() connects them all.

nested = os.path.join("reports", "2024", "january.csv")
print(nested)  # reports/2024/january.csv

Extracting parts of a path

FunctionReturns
os.path.basename(path)The filename at the end
os.path.dirname(path)Everything except the filename

Instructions

Build and inspect file paths using the os module.

  1. Import os.
  2. Create folder = "data" and filename = "sales.txt". Create path = os.path.join(folder, filename). Call print(path).
  3. Create nested_path = os.path.join("reports", "2024", "january.csv"). Call print(nested_path).
  4. Call print(os.path.basename(nested_path)) to print just the filename.
  5. Call print(os.path.dirname(nested_path)) to print just the directory.