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
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.
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.
Use the str. split() method to split a string on the backslashes, e.g. my_list = my_str. split('\\') .
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,)
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