Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice the file path in Python

Tags:

python

I am very new to Python as well a programming, and I would like to slice the folder path. For example, if my original path is:

C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/

I would like to get the path like this:

C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/

What are the methods of doing this in Python?

like image 305
arul Avatar asked Aug 11 '26 19:08

arul


1 Answers

You could use the pathlib module:

from pathlib import Path

pth = Path('C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/')

print(pth)
print(pth.parent)
print(pth.parent.parent)  # C:/Users/arul/Desktop/jobs/project_folder

The module has a lot more of very convenient methods for handling paths: your problem could also be solved using parts like this:

print('/'.join(pth.parts[:-2]))

In Python 2.7 you could build your own parts function using os.path:

from os import path

pth = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/'

def parts(pth):
    ret = []
    head, tail = path.split(pth)
    if tail != '':
        ret.append(tail)
    while head != '':
        head, tail = path.split(head)
        ret.append(tail)
    return ret[::-1]

ret = path.join(*parts(pth)[:-2])
print(ret)  # C:/Users/arul/Desktop/jobs/project_folder
like image 176
hiro protagonist Avatar answered Aug 14 '26 08:08

hiro protagonist



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!