Friday, August 30, 2013

Python get path

The task is to rip the directory part from a full path file name. Split is handy, but not helpful since doing something like splitting on '/' would just get any number of separate pieces, using the number of pieces argument isn't helpful because the directory could have any number of pieces. Python has a function called rsplit, problem solved except that for some reason it's not in my ridiculously old revision of Python (2.3).

There is a whole library that does this called ntpath. Tried it, it's great. It also seems to autonomously convert Windows paths to *nux paths. Here's the link:

http://stackoverflow.com/questions/8384737/python-extract-file-name-from-path-no-matter-what-the-os-path-format

But it turns out that os.path.split would work just as well, plus os.path does all kinds of other great stuff too:

http://docs.python.org/2/library/os.path.html

I also learned that in my version of Python, and probably in all later versions, it is possible to use regular split with negative numbers to transverse the split array from the right, thusly:

filename=fullpath.split('/')[-1]

In order to take a full path file name and get the lowest directory level from the path, the easiest trick seems to be to use os.path.dirname and then use split with -1:

path=os.path.dirname(fullpath)
bottom_dir = path.split('/')[-1]