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:
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.