99

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 to use .split('/') but it's not clean, since you have to add the final /, and it's not compatible with all OSes.

nlassaux
  • 2,335
  • 2
  • 21
  • 35

5 Answers5

179

Use os.path.dirname(filename).

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
13

You can import os

>>> filepath
'/a/path/to/my/file.txt'
>>> os.path.dirname(filepath)
'/a/path/to/my'
>>> 
aayoubi
  • 11,285
  • 3
  • 22
  • 20
6
(dirname, filename) = os.path.split(path)
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
5

Since Python 3.4 you can use Pathlib.

from pathlib import Path

path = Path("/a/path/to/my/file.txt")
print(path.parent)
Arigion
  • 3,267
  • 31
  • 41
4

Check subs of os.path

os.path.dirname('/test/one')
sloth
  • 99,095
  • 21
  • 171
  • 219
tuxuday
  • 2,977
  • 17
  • 18