In Python, how should one extract the second-last directory name in a path?

d3pd picture d3pd · Feb 5, 2015 · Viewed 8.1k times · Source

I have a string like the following:

/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore

How should I extract the "2.0.24" from this string? I'm not sure how to split the string using the slashes (in order to extract the second last element of the resultant list) and I'm not sure if this would be a good approach. What I have right now is the following:

"/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore".split("/RootCore")[0].split("AnalysisTop/")[1]

Answer

AlG picture AlG · Feb 5, 2015

You can also do:

import os
x = "/cvmfs/atlas.cern.ch/repo/sw/ASG/AnalysisTop/2.0.24/RootCore"
os.path.split(os.path.split(x)[0])[1]

results in

'2.0.24'