3

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

4
  • 1
    Don't assume that the path separator is always / if you are planning to run this on different operating systems. Commented Apr 15, 2019 at 23:32
  • 1
    Its for an internal project where we could set a standard, but you are right, someone might input a filepath from a different OS where its \ instead of / Commented Apr 15, 2019 at 23:34
  • Possible duplicate of Extract a part of the filepath (a directory) in Python Commented Apr 15, 2019 at 23:44
  • Best way to do this is using the OS-independent pathlib module. Commented May 29, 2021 at 7:52

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

Comments

5

Please try this

fullpath = '/path/to/some/file.jpg' import os os.path.dirname(fullpath) 

Comments

4

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.

Comments

0

With String rfind method.

fullpath = '/path/to/some/file.jpg' index = fullpath.rfind('/') fullpath[0:index] 

4 Comments

What about this: '/path/to/some//file.jpg' or 'C:\path\to\some\file.jpg'?
Based on the users given and then criteria, this should be good. But I agree this would not work in case of different OS.
It doesn't work correctly with my first example either. We should not suggest fail-prone methods when there is a documented, platform agnostic built-in method of doing something, such as the 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.
Okay, makes sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.