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


Recommended Answers

All 5 Replies

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.


As a oneliner ...

import os

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

print os.sep.join(s.split(os.sep)[:2])  # C:\path1

cool, thanks for help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.