Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split path in Python

Tags:

python

path

split

How I could split this:

C:\my_dir\repo\branch

to:

['C:\my_dir', rest_part_of_string]

where rest_part_of_string can be one string or could be splitted every \. I don't care about rest, i just want first two elements together.

like image 281
Mateusz Szymański Avatar asked Jul 13 '26 00:07

Mateusz Szymański


1 Answers

python 3.4 has methods for that (note the forward slashes instead of the backslashes (or double the backslashes))

pathlib documentation

# python 3.4
from pathlib import Path

p  = Path('C:/my_dir/repo/branch')

print(p.parent)
print(p.name)

for what you need parts is interesting:

print(p.parts)
# -> ('C:', 'my_dir', 'repo', 'branch')
print('\\'.join(p.parts[:2]), ' -- ', '\\'.join( p.parts[2:])) 
# -> C:\my_dir  --  repo\branch

in python 2.7 this needs a bit more work:

import os

p = 'C:/my_dir/repo/branch'

def split_path(path):
    parts = []
    while 1:
        path, folder = os.path.split(path)
        if folder:
            parts.append(folder)
        else:
            if path:
                parts.append(path)
            break
    parts.reverse()
    return parts

parts = split_path(p)
print('\\'.join(parts[:2]), ' -- ', '\\'.join(parts[2:]))
# -> C:\my_dir  --  repo\branch
like image 186
hiro protagonist Avatar answered Jul 15 '26 13:07

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!