Mostly Linux & Python syntax notes and hyperlinks.

Thursday, June 23, 2011

python: get the last directory name in a path

If I want to pull just the parent directory name out of a long path to a file:
>>> import os
>>> pth="/abeja/blanca/zumbas/ebria/de/miel/en/mi/alma/y.te.tuerces"
>>> os.path.split(os.path.dirname(pth))[1]
'alma'
>>>

7 comments:

  1. You da' woman! Thank you!

    ReplyDelete
  2. I was searching for this solution in a lot of websites and wasted almost a couple of hours for this one line.

    Thanks a TON !! Keep the good work going ...

    ReplyDelete
  3. You can use Long Path Tool, it works for such problems..

    ReplyDelete
  4. Thank You, exactly what I was looking for.

    ReplyDelete