0

I have a path string something like '/foo/bar1/bar2/test.txt'. I want to retrieve just '/foo/bar1/' from the string and want to ignore the rest. I tried doing that with \/([\w\s]+)\/|,(?!\w)+? but that didn't help.

Can someone help me with this ?

Thanks in advance

2
  • what exactly are you trying to do here? Commented Mar 28, 2012 at 7:37
  • What is special with /foo/bar1/? For regex, there must be a strict indicator for selecting the right part. Or for eumiro's answer, change in the number of / or changing the string might resolve a wrong answer.. What do you really try to do here?... Commented Mar 28, 2012 at 7:52

1 Answer 1

2
s = '/foo/bar1/bar2/test.txt'

'/'.join(s.split('/')[:3])

# returns '/foo/bar1'

Change that 3 to the appropriate number. For further path manipulation have a look at os.path methods.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks eumiro :) ... regex is not always the best solution i guess
In general, when working with file paths you nearly always want to use either plain string methods (like split) or the os.path methods, which are robust across operating systems and file path conventions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.