equivalent of Ruby's Pathname?

alex23 wuwei23 at gmail.com
Thu Feb 4 03:08:52 CET 2010

On Feb 4, 8:47 am, Phlip <phlip2... at gmail.com> wrote:
> Yes, calling os.path.walk() and os.path.join() all the time on raw
> strings is fun, but I seem to recall from my Ruby days a class called
> Pathname, which presented an object that behaved like a string at
> need, and like a filesystem path at need. path + 'folder' would
> call .join() and insert the / correctly, for example.
> What's the best equivalent in Python-land?

It's no longer supported, but the 3rd party 'path' module used to be
the go-to module for this:

>>> from path import path
C:\Python26\lib\site-packages\path.py:32: DeprecationWarning: the md5
module is deprecated; use hashlib instead
  import sys, warnings, os, fnmatch, glob, shutil, codecs, md5
>>> c = path('C:\\')
>>> c.listdir()
[path(u'C:\\AUTOEXEC.BAT'), path(u'C:\\boot.ini'), ...]
>>> (c + 'python26').listdir()
[path(u'C:\\python26\\circuits.pth_disabled_for_egg'), path(u'C:\
\python26\\DLLs'), ...]
>>> (c / 'python26').listdir()
[path(u'C:\\python26\\circuits.pth_disabled_for_egg'), path(u'C:\
\python26\\DLLs'), ...]

I've hand edited the results for brevity...

The module could do with some TLC to bring it up to date, but warning
aside it still seems to work fine under 2.6.

(From memory, I think the original author gave up when it became clear
it would never be integrated into the standard lib[1], which is a
shame, I think there's scope for a pathtools addition to the lib that
provides this level of convenience...)

There was also a PEP with another possible implementation:

Hope this helps.

More information about the Python-list mailing list