3

Do you guys know a more intelligent way to do this ?

os.path.split(os.path.split(os.path.split(os.getcwd())[0])[0])[0]

os.getcwd() is for example:

/my/path/to/my/directory

I should get

/my/path/

That is really an exaggeration and duplication of the os.path.split()

Thanks

4
  • Why not try a regex after calling os.getcwd()? Commented Jun 7, 2017 at 18:37
  • 3
    Have you heard of os.path.dirname? Commented Jun 7, 2017 at 18:37
  • @user2357112 Surely he has, as it's mentioned in the documentation of the function he's using... Commented Jun 7, 2017 at 18:41
  • @user2357112 better but still repetitive if I have to 3 of them ... Commented Jun 7, 2017 at 18:43

2 Answers 2

6

I would suggest you using os.sep:

os.sep.join(os.getcwd().split(os.sep)[:-3])

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

Comments

4

You can use pathlib

from pathlib import Path
path = Path('/my/path/to/my/directory').parents[2]
print(path)

>>> /my/path

As of Python 3.4, pathlib is part of the standard libraries, but you can install in earlier versions

pip install pathlib

2 Comments

Works well but you have to download pathlib. It is already in your site-packages ?
@MathieuChâteauvert I just updated my answer with that information

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.