没有基名的文件路径

如何得到没有文件基名的文件路径?

类似于 /a/path/to/my/file.txt-> /a/path/to/my/

.split()试过,没有成功。

60313 次浏览

Use os.path.dirname(filename).

Check subs of os.path

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

You can import os

>>> filepath
'/a/path/to/my/file.txt'
>>> os.path.dirname(filepath)
'/a/path/to/my'
>>>
(dirname, filename) = os.path.split(path)

Since Python 3.4 you can use Pathlib.

from pathlib import Path


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