84

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.

desertnaut
  • 52,940
  • 19
  • 125
  • 157
nlassaux
  • 2,114
  • 2
  • 17
  • 32

5 Answers5

151

Use os.path.dirname(filename).

Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842
10

You can import os

>>> filepath
'/a/path/to/my/file.txt'
>>> os.path.dirname(filepath)
'/a/path/to/my'
>>> 
aayoubi
  • 10,299
  • 3
  • 19
  • 20
5
(dirname, filename) = os.path.split(path)
Igor Chubin
  • 57,130
  • 8
  • 114
  • 135
4

Check subs of os.path

os.path.dirname('/test/one')
sloth
  • 95,484
  • 19
  • 164
  • 210
tuxuday
  • 2,843
  • 16
  • 18
2

Since Python 3.4 you can use Pathlib.

from pathlib import Path

path = Path("/a/path/to/my/file.txt")
print(path.parent)
Arigion
  • 2,889
  • 29
  • 41