liveBook · Manning

Relative pathname

As explained in The Quick Python Book, Fourth Edition

A relative pathname identifies a filesystem location in relation to an external anchor such as an absolute pathname or the current working directory.

A relative pathname identifies a file or directory from a starting point that is not written into the pathname. Unlike an absolute pathname, it does not specify a location from the filesystem root. The same relative pathname can therefore identify different locations when its starting point changes. section 12.2.1

Choose an anchor

On Windows, appending `Start Menu\Programs\Startup` to `C:\Users\Administrator` identifies that administrator’s Startup folder. Append it to `C:\Users\myuser` instead, and it identifies a folder under a different user. section 12.2.1

Python filesystem calls commonly use the current working directory as the implicit anchor. For example, `os.listdir('sample_data')` lists a directory beneath the current working directory. Check that anchor with `os.getcwd()`; changing it with `os.chdir('sample_data')` changes how subsequent relative paths are interpreted. section 12.2.1 section 12.2.2

Build and use relative paths without hard-coding a platform’s separator:

  • Use `os.path.join('bin', 'utils', 'disktools')` to combine path components; the result uses the operating system’s path convention. section 12.2.4
  • Use `os.curdir` for the current directory and `os.pardir` for its parent. For example, `os.listdir(os.curdir)` lists entries in the current working directory. section 12.2.6
  • `pathlib` also provides path-combining and filesystem operations for relative and absolute paths. section 12.7

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines relative paths, works through two anchoring methods, and demonstrates construction and working-directory behavior without examining filesystem internals.
Examples
Shows a Windows Startup path under two user directories and Python calls that join components or list the current directory.
What it assumes
Assumes basic familiarity with Python strings and function calls while defining relative and absolute pathnames.
What you can do after
Apply it via Python’s os.path.join and os.listdir to construct portable paths and access directories relative to the current working directory.
How it connects
Connects relative pathnames to absolute pathnames, the current working directory, os.path.join, and pathlib.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.