arul
arul

Reputation: 33

How to slice the file path in 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?

Upvotes: 3

Views: 6881

Answers (3)

hiro protagonist
hiro protagonist

Reputation: 46869

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

Upvotes: 6

Sid
Sid

Reputation: 96

You can do something like this:

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

folder.rsplit('/', 3)[0]

str.rsplit() basically returns a list of the words in the string, separated by the delimiter string (starting from right).

Please have a look at documentation for more details on this method.

Upvotes: -1

cs95
cs95

Reputation: 402533

If you just want to split on elements, then use this.

>>> path = 'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/elements/MexicoCity-Part1/'
>>> path.split('elements')[0]
'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/'

One drawback of this approach is that it'll fail if you encounter the word elements in your path multiple times. In that case, you can do something like:

>>> '/'.join(path.split('/')[:-3]) + '/'
'C:/Users/arul/Desktop/jobs/project_folder/shots/shot_folder/'

Assuming you know the depth of the path you need.

Upvotes: 0

Related Questions