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 subfolderAn 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") # WindowsBuilding 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/macOSPass 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.csvExtracting parts of a path
| Function | Returns |
|---|---|
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.
- Import
os. - Create
folder = "data"andfilename = "sales.txt". Createpath = os.path.join(folder, filename). Callprint(path). - Create
nested_path = os.path.join("reports", "2024", "january.csv"). Callprint(nested_path). - Call
print(os.path.basename(nested_path))to print just the filename. - Call
print(os.path.dirname(nested_path))to print just the directory.
# Step 1: Import os # Step 2: Create folder and filename variables, join them, and print # Step 3: Create nested_path from "reports", "2024", "january.csv" and print # Step 4: Print only the filename part of nested_path # Step 5: Print only the directory part of nested_path
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding