Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Extract everything in a filepath, after a certain directory

Let’s say I have a folder like this.

/home/user/dev/Project/media/image_dump/images/02_car_folder

Everything after the media directory should be kept. The remaining should be removed.

/media/image_dump/images/02_car_folder

I was originally doing it this way but as more subdirectories were added to different folders started generating invalid filepaths

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

split_absolute = [os.sep.join(os.path.normpath(y).split(os.sep)[-2:]) for y in absolute_path]

The problem this causes is that once you start going deeper, the media path is cut out of the filepath all together.

So if I went into

media/image_dump/images/02_car_folder/

The filepath now becomes this, when it needs to include everything up to /media.

/images/02_car_folder

What are some ways to actually handle this? I won’t know users filepaths will be leading up to media, but I know that everything after media is what should be kept regardless, no matter how deep their folders go.

>Solution :

I think you can achieve what you want quite easily using Path.parts:

from pathlib import Path

path = "/home/user/dev/Project/media/image_dump/images/02_car_folder"
parts = Path(path).parts
stripped_path = Path(*parts[parts.index("media"):])

Result:

>>> print(stripped_path)
media/image_dump/images/02_car_folder
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading