-4

Any clean way to do path calculation rather than string split in Python?

working_dir = "/a/b/c/d/e/f/g", given_dir = "d/e/f/g"

How do I get parent path "/a/b/c"?

pepero
  • 7,095
  • 7
  • 41
  • 72
  • `working_dir.rstrip(given_dir)`? what have you tried? – Sayse Feb 05 '18 at 09:16
  • Possible duplicate of [How do I get the parent directory in Python?](https://stackoverflow.com/questions/2860153/how-do-i-get-the-parent-directory-in-python) – hoefling Feb 05 '18 at 09:16
  • @Sayse, no way to do path calculation rather than string calculation? – pepero Feb 05 '18 at 09:21
  • Thats great. what about the rest of my comment? – Sayse Feb 05 '18 at 09:21
  • i tried, except treating it like string, not able to find a way to treat it like path. – pepero Feb 05 '18 at 09:27
  • @pepero So basically you don't know the exact working directory and you only knows that given_dir with that you want to find remaining full path , Is it like that ? – Vikas Periyadath Feb 05 '18 at 09:34
  • @VikasDamodar, i know working_dir. i just expect something opposite of os.path.join(), .e.g, os.path.disjoin(path, *paths), or some pythonic way, which could do the path calculation. – pepero Feb 05 '18 at 09:38

1 Answers1

0

The top directory you can get with:

os.path.split(working_dir)[0]

So you just do that the number of times you need...

mrCarnivore
  • 4,638
  • 2
  • 12
  • 29
  • did you read my quesiton? what is the result of your code? "/a/b/c/d/e/f"? – pepero Feb 05 '18 at 09:18
  • Yes, that is correct. On the resulting string you can just execute the same command again to get the parent directory of that. Depending on how many levels you want to go up. There are other ways as well. But for finding the direct parent this is the best way. – mrCarnivore Feb 05 '18 at 09:21
  • sorry, that is not what I want to ask. what if i have "d/e/f/g/h/i/j/k/l/m", need ten levels up? – pepero Feb 05 '18 at 09:25
  • From my answer you should be able to extrapolate and adapt that example to fit your needs. Strictly speaking, though, everything you want to do is string manipulation which you explicitly do not want to do... So I am unsure how to further help you. String manipulation would also be much more efficient.... – mrCarnivore Feb 05 '18 at 09:27