Skip to content Skip to sidebar Skip to footer

Python: Split Hard Coded Path

I need to split a path up in python and then remove the last two levels. Here is an example, the path I want to parse. I want to parse it to level 6. C:\Users\Me\level1\level2\leve

Solution 1:

Split the path into all its parts, then join all the parts, except the last two.

import os

seperator = os.path.sep
parts = string.split(seperator)
output = os.path.join(*parts[0:-2])

Solution 2:

You can either use the split function twice:

os.path.split(os.path.split(a)[0])[0]

This works since os.path.split() returns a tuple with two items, head and tail, and by taking [0] of that we'll get the head. Then just split again and take the first item again with [0].

Or join your path with the parent directory twice:

os.path.abspath(os.path.join(a, '..', '..'))

You can easily create a function that will step back as many steps as you want:

def path_split(path, steps):
    for i in range(steps + 1):
        path = os.path.split(path)[0]
    returnpath

So

>>>path_split("C:\Users\Me\level1\level2\level3\level4\level5\level6\level7\level8", 2)
"C:\Users\Me\level1\level2\level3\level4\level5\level6\"

Solution 3:

os.path.split(path) gives the whole path except the lastone, and the last one in a tuple. So if you want to remove the last two,

os.path.split(os.path.split(your_path)[0])[0]

Post a Comment for "Python: Split Hard Coded Path"