Hi everybody!

I need to split my path, let's say' "C:\path1\path2\path3\path4" into separate strings... Not sure how to do that, I've tried os.path.split / splitdrive etc. but it always give me just 2 arguments

I need to get "C:\path1" from this path string for example, which would be the root folder of my project structure

Maybe I could just walk top by hierarchy, in my case I need 2 steps to get the result I need. I have found os.path.walk command, but I'm afraid it does not what I need

Thanks!

I have found that I can do this by splitting path string with the mystring.split() command. Got to try it

maybe there is any other way, to operate directly with my path object?

What you have done is the easiest way to do it because you have control. Remember that you have to parse the string no matter what the method. Even when Python has a method to do it, the string still has to be parsed, so you should have no problem with doing it yourself. It would be slightly more efficient to find the second "\" and slice there, but is more trouble than it is worth.

If you want to be portable across *nix and windows, try something like:

import os
ps = '/tmp/my/path'.split(os.sep)

This will split the path into separate elements without you having to specify '/' or '\\' as separator.

HTH

As a oneliner ...

import os

s = "C:\path1\path2\path3\path4"

print os.sep.join(s.split(os.sep)[:2])  # C:\path1
This question has already been answered. Start a new discussion instead.