Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Split path recursively

I am trying to split a path given as a string into sub-parts using the "/" as a delimiter recursively and passed into a tuple. For ex: "E:/John/2012/practice/question11" should be ('E:', 'John', '2012', 'practice', 'question11').

So I've passed every character excluding the "/" into a tuple but it is not how I wanted the sub-parts joint as displayed in the example. This is a practice question in homework and would appreciate help as I am trying to learn recursion.

Thank You so much

like image 428
user1757703 Avatar asked Nov 22 '12 04:11

user1757703


People also ask

How do you split a path in Python?

path. split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that.

How do you split paths?

The Split-Path cmdlet returns only the specified part of a path, such as the parent folder, a subfolder, or a file name. It can also get items that are referenced by the split path and tell whether the path is relative or absolute. You can use this cmdlet to get or submit only a selected part of a path.

How do you split a path by a slash in Python?

Use the str. split() method to split a string on the backslashes, e.g. my_list = my_str. split('\\') .


1 Answers

Something like this

>>> import os
>>> s = "E:/John/2012/practice/question11"
>>> os.path.split(s)
('E:/John/2012/practice', 'question11')

Notice os.path.split() doesn't split up the whole path as str.split() would

>>> def rec_split(s):
...     rest, tail = os.path.split(s)
...     if rest == '':
...         return tail,
...     return rec_split(rest) + (tail,)
...
>>> rec_split(s)
('E:', 'John', '2012', 'practice', 'question11')

Edit: Although the question was about Windows paths. It's quite easy to modify it for unix/linux paths including those starting with "/"

>>> def rec_split(s):
...     rest, tail = os.path.split(s)
...     if rest in ('', os.path.sep):
...         return tail,
...     return rec_split(rest) + (tail,)
like image 67
John La Rooy Avatar answered Sep 21 '22 15:09

John La Rooy