Path to a file without basename

Python

Python Problem Overview


How can I get the path of a file without the file basename?

Something like /a/path/to/my/file.txt --> /a/path/to/my/

Tried with .split() without success.

Python Solutions


Solution 1 - Python

Use os.path.dirname(filename).

Solution 2 - Python

You can import os

>>> filepath
'/a/path/to/my/file.txt'
>>> os.path.dirname(filepath)
'/a/path/to/my'
>>> 

Solution 3 - Python

(dirname, filename) = os.path.split(path)

Solution 4 - Python

Check subs of os.path

os.path.dirname('/test/one')

Solution 5 - Python

Since Python 3.4 you can use Pathlib.

from pathlib import Path

path = Path("/a/path/to/my/file.txt")
print(path.parent)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnlassauxView Question on Stackoverflow
Solution 1 - PythonDaniel RosemanView Answer on Stackoverflow
Solution 2 - PythonaayoubiView Answer on Stackoverflow
Solution 3 - PythonIgor ChubinView Answer on Stackoverflow
Solution 4 - PythontuxudayView Answer on Stackoverflow
Solution 5 - PythonArigionView Answer on Stackoverflow