Path to a file without basename [duplicate]

Solution 1:

Use os.path.dirname(filename).

Solution 2:

You can import os

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

Solution 3:

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

Solution 4:

Check subs of os.path

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

Solution 5:

Since Python 3.4 you can use Pathlib.

from pathlib import Path

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