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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With