I am looking for a simple Pythonic way to parse Linux style path, while keeping the basename and the directory path in respective variables.
Asked
Active
Viewed 147 times
-5
-
6https://docs.python.org/2/library/os.path.html#os.path.basename – JacobIRR Aug 02 '19 at 18:54
-
Possible duplicate of [Extracting extension from filename in Python](https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python) – d_kennetz Aug 02 '19 at 18:59
-
Possible duplicate of [Extract file name from path, no matter what the os/path format](https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format) – Andras Deak -- Слава Україні Aug 02 '19 at 19:27
-
I updated the question. I meant to specify that I was looking for a way to separate the dir-path from the basename into two separate variables, while not affecting the input string or knowing the basename prior. – sbaby171 Aug 02 '19 at 21:07
2 Answers
1
The modern pythonic way is to use Pathlib, which provides an object-oriented interface for path manipulation:
from pathlib import Path
thing = Path('my/path').name
The oldschool (and still just fine) way to do it is to use os.path
.
import os.path
thing = os.path.basename('my/path')

kojiro
- 74,557
- 19
- 143
- 201
-3
One issue with this solution, is that it assumes that there are no repeats of the basename in the full path. Now, typically that is true, this solution is technically not true.
import os
x = "/home/first/second/third/main.cpp"
basename = os.path.basename(x)
dir_path = x.split(basename)[0]
A better solution would be:
import os
x = "/home/first/second/third/main.cpp"
basename = os.path.basename(x)
dir_path = "/".join(x.split("/")[:-1])

sbaby171
- 68
- 7
-
2This solution appears to violate the PEP8 section on [Blank Lines](https://www.python.org/dev/peps/pep-0008/#blank-lines). I would assume any Pythonic solutions would adhere to PEP8. – Dair Aug 02 '19 at 19:03
-
Also, this would be a better answer if you explained how to code answers the question. – pppery Aug 02 '19 at 19:54