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
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.
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.
With String rfind method.
fullpath = '/path/to/some/file.jpg' index = fullpath.rfind('/') fullpath[0:index] '/path/to/some//file.jpg' or 'C:\path\to\some\file.jpg'?os.path.split method suggested by @LevLevitsky. The OP has suggested a similar method themselves but they are looking for a better method because they think it is open to errors.
/if you are planning to run this on different operating systems.pathlibmodule.