Reputation: 6169
Given a file path
/path/to/some/file.jpg
How would I get
/path/to/some
I'm currently doing
fullpath = '/path/to/some/file.jpg'
filepath = '/'.join(fullpath.split('/')[:-1])
But I think it is open to errors
Upvotes: 3
Views: 7128
Reputation: 3554
Using pathlib
you can get the path without the file name using the .parent
attribute:
from pathlib import Path
fullpath = Path("/path/to/some/file.jpg")
filepath = str(fullpath.parent) # /path/to/some/
This handles both UNIX and Windows paths correctly.
Upvotes: 4
Reputation: 791
Please try this
fullpath = '/path/to/some/file.jpg'
import os
os.path.dirname(fullpath)
Upvotes: 4
Reputation: 65791
With os.path.split
:
dirname, fname = os.path.split(fullpath)
Per the docs:
Split the pathname path into a pair,
(head, tail)
where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty.
os.path
is always the module suitable for the platform that the code is running on.
Upvotes: 13