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.
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!
There’s a (somewhat) maintained fork of this on github also:
http://github.com/Singletoned/forked-path
WHY have I not been using this?!
Spread the word, my good brother. Let all convert to the goodness of Path().
There’s a reason this isn’t already implemented in Python.
http://www.python.org/dev/peps/pep-0355
Interesting. I did not know it was even considered to be included in the standard library. That makes it pretty close to being “official”. Guess some of the string methods it inherits are not compatible. Oh well, hasn’t been an issue for me yet. Great to see that PEP though, thanks.