Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Treating Pathnames as Objects

Credit: David Ascher

Problem

You want to manipulate path objects as if they were sequences of path parts.

Solution

Although it is only available this elegantly in Python 2.2 and later, you can create a subclass of the string type that knows about pathnames:

_translate = { '..': os.pardir }
class path(str):
   def _ _str_ _(self):
       return os.path.normpath(self)
   def _ _div_ _(self, other):
       other = _translate.get(other, other)
       return path(os.path.join(str(self), str(other)))
   def _ _len_ _(self):
       return len(splitall(str(self)))
   def _ _getslice_ _(self, start, stop):
       parts = splitall(str(self))[start:stop]
       return path(os.path.join(*parts))
   def _ _getitem_ _(self, i):
       return path(splitall(str(self))[i])

Note that this solution relies on Recipe 4.16.

Discussion

I designed this class after I had to do a lot of path manipulations. These are typically done with a function such as os.path.join, which does the job well enough, but is somewhat cumbersome to use:

root = sys.prefix
sitepkgs = os.path.join(root, 'lib', 'python', 'site-packages')

To use this recipe, the first path must be created with the path function. After that, divisions are all that we need to append to the path:

root = path(sys.prefix)
sitepkgs = root / 'lib' / 'python' / 'site-packages'

As an additional bonus, you can treat the path as a sequence of path parts:

>>> print sitepkgs
C:\Apps\Python22\lib\python\site-packages
>>> print len(sitepkgs)
6
>>> sitepkgs[0], sitepkgs[1], sitepkgs[-1]
('C:\\', 'Apps', ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata