Kent's Korner
by Kent S Johnson

2007-02-18 20:01:01

The path module

Jason Orendorff's path module is one of my favorite Python add-ons. It collects a variety of functions from the os, os.path and shutil modules into a single handy class. When I write a program to deal with a bunch of files in some way, the first line I write is often import path.

The Basics

A path object is created from a string. Paths can be joined using the / operator:

>>> import path
>>> p = path.path(r'F:\Tutor')
>>> p
path(u'F:\\Tutor')
>>> p / 'Tk'
path(u'F:\\Tutor\\Tk')

Files and Directories

The files() and dirs() methods list files and directories. They can take file globs as arguments. The list elements themselves are path objects:

>>> p.dirs()
[path(u'F:\\Tutor\\weekday'), path(u'F:\\Tutor\\SPOJ')]
>>> p.files('*.py')
[path(u'F:\\Tutor\\AllTheSame.py'), ...]

If you want to list files and directories recursively, use walkfiles() or walkdirs(). Both methods take an optional glob argument and return a generator that yields path objects.

Attributes

path objects have several useful attributes including name, ext and parent:

>>> f=p.files()[0]
>>> f
path(u'F:\\Tutor\\AllTheSame.py')
>>> f.name
u'AllTheSame.py'
>>> f.ext
u'.py'
>>> f.parent
path(u'F:\\Tutor')

A path is a string

path is a subclass of str (a Python string) so you can use a path anywhere you can use a string:

>>> for line in open(f):
...   print line

But wait, there's more!

path has more nice features such as relpath() for computing relative paths, and methods for reading and writing files. Also the functions in os.path, such as isdir(), isfile() and exists, are methods of path. See the docs for details.

PEP 355

Many people think the path module is great and that something like it should be part of the standard library. PEP 355 proposes such a module. Unfortunately (IMO), not everyone sees the need for path. The major objections are

  • path should not subclass str because not all string operations make sense for paths
  • `` path`` doesn't add any new capabilities to the standard library so it is redundant and unneccessary.

Guido van Rossum, in particular, finds path to be redundant and has pronounced PEP 355 dead.

 
© Kent S Johnson Creative Commons License

Short, introductory essays about Python.

kentsjohnson.com

Kent's Korner home

Weblog

Other Essays