Ari
Ari

Reputation: 6169

Get file path without file name

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

Answers (4)

martin-martin
martin-martin

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

Please try this

fullpath = '/path/to/some/file.jpg'

import os
os.path.dirname(fullpath)

Upvotes: 4

Lev Levitsky
Lev Levitsky

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

St1id3r
St1id3r

Reputation: 333

With String rfind method.

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

Upvotes: 0

Related Questions