path(), the awesomest class

Categories: Python
Tags: No Tags
Comments: 6 Comments
Published on: July 10, 2011

Jason Orendorff wrote an awesome module some years ago to make it quick and easy to manipulate file paths and file names. I was fortunate enough to be exposed to this module and class via PyMEL’s package which included it.

Here is our test path and we’ll slice it and dice it in all kinds of ways:
‘c:/temp/test/myTestFile.txt’

Here’s how you cast a string into the class:

from path import path
filePath = 'c:/temp/test/myTestFile.txt'
fpPathObj = path(filePath)
fpPathObj
# Result: path('c:/temp/test/myTestFile.txt') # 

There are a 167 methods on this class, so you can obviously get practically anything you want. Here are some of my favorite methods:

fpPathObj.basename()
# Result: 'myTestFile.txt' # 

# .name is a property which returns the same
fpPathObj.name
# Result: 'myTestFile.txt' #

# namebase returns fileName only w/o extension
fpPathObj.namebase
# Result: 'myTestFile' #

# return directory above file
fpPathObj.parent
# Result: path('c:/temp/test') # 

# check extension
fpPathObj.endswith('txt')
# Result: True # 

# check existance
fpPathObj.exists()
# Result: True # 

# check to see if folder type
fpPathObj.parent.isdir()
# Result: True #


And many, many more. I use the above ones practically everyday, though.

Last example is my latest usage I used today. You can daisy chain the .parent calls to traverse up the chain:

fpPathObj.parent.parent.name
# Result: 'temp' # 

So if you’re using Maya, then your probably be using PyMEL by now (if not, get with it and watch THIS). If so, you already have the path class in a convenient location. You can simply import it like this:

from pymel.util.path import path

If you’re in MotionBuilder or other DCC app using Python, you can get it here: http://pypi.python.org/pypi/path.py/2.2

Enjoy one of the handier classes any Tech Artist can add to his/her toolbox.

Post to Twitter

6 Comments
  1. lee says:

    this looks fantastic, I know i’ve used path() before but didnt really take a proper look into it, i’ve been using classes all over the shop the pull the info I could have just gotten with this…

    especially with the daisying 🙂

    cheers!

  2. Seth says:

    There’s a (somewhat) maintained fork of this on github also:

    http://github.com/Singletoned/forked-path

  3. Matt says:

    WHY have I not been using this?!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Welcome , today is Wednesday, May 31, 2023