Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]
like image 212
d3pd Avatar asked Feb 05 '15 15:02

d3pd


People also ask

How do I get the last part of a path in Python?

os. path. basename() - It returns the last part of the path.

How do I get the path of a directory in Python?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

How do I separate the filename and path in Python?

split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that. In the above example 'file. txt' component of path name is tail and '/home/User/Desktop/' is head.


1 Answers

cross platform solution:

import os
'your/path'.split(os.path.sep)[-2]
like image 81
Daniel Braun Avatar answered Sep 24 '22 03:09

Daniel Braun