Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file path without file name

Tags:

python

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

like image 885
Ari Avatar asked Jan 24 '26 19:01

Ari


2 Answers

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.

like image 68
Lev Levitsky Avatar answered Jan 26 '26 10:01

Lev Levitsky


Please try this

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

import os
os.path.dirname(fullpath)
like image 27
Ravishankar Sivasubramaniam Avatar answered Jan 26 '26 09:01

Ravishankar Sivasubramaniam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!