liveBook · Manning

Os.path.dirname

As explained in The Quick Python Book, Fourth Edition

os.path.dirname is a Python function that returns the directory portion of a filesystem pathname, excluding its final component.

os.path.dirname returns the directory portion of a filesystem pathname, excluding its final file or directory name. section 12.2.4

Extract a directory

For `some/directory/path.jpg`, `os.path.dirname` returns `'some/directory'`. Use `os.path.basename` when you need the final component instead.

Related pathname operations separate complementary parts:

  • `os.path.split` returns the directory portion and basename as a two-element tuple. section 12.2.4
  • `os.path.splitext` separates a pathname from its dotted extension. section 12.2.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the returned portion and demonstrates it with a pathname, without detailing implementation internals or edge cases.
Examples
Uses `some/directory/path.jpg` to show the directory result alongside the basename and extension alternatives.
What you can do after
Apply os.path.dirname to obtain the directory portion of a constructed or existing pathname.
How it connects
Connects os.path.dirname with os.path.split, os.path.basename, and os.path.splitext for decomposing pathnames.

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.