0

Is there a simpler way to get a string of a parent directory than doing the following?

'/'.join(os.getcwd().split('/')[:-1])
David542
  • 104,438
  • 178
  • 489
  • 842
  • 2
    possible duplicate of [Get parent directory in Python](http://stackoverflow.com/questions/2860153/get-parent-directory-in-python) – Greg Hewgill Apr 09 '12 at 19:46
  • 2
    Please don't assume `os.set == '/'` like that. There are ready-made functions for this in `os.path`: `split`, `join`, `basename`, etc. –  Apr 09 '12 at 19:50

3 Answers3

3

I believe this would be much simpler for you

os.path.abspath(os.path.pardir)

or even simpler

os.path.dirname(os.getcwd())
Abhijit
  • 62,056
  • 18
  • 131
  • 204
1

I don't know of a method that does it but I would do something like:

os.path.abspath(os.path.join(os.getcwd(), os.pardir))

EDIT: This way works but Ixanezis way is probably better.

Community
  • 1
  • 1
Sionide21
  • 2,202
  • 2
  • 21
  • 30
  • os.getcwd() is already absolute path, so os.path.abspath is redundant and os.path.join(x, os.pardir) is almost the same as os.path.dirname(x) – Zart Apr 09 '12 at 19:53
  • `os.path.join(os.getcwd(), os.pardir)` basically just appends `/..` to the path, calling `os.path.abspath` on it then converts it back down. `dirname` is probably a better approach, I have edited my answer to reflect that. – Sionide21 Apr 09 '12 at 20:04
1

Well, this method may be useful:

os.path.dirname(os.getcwd())
Ixanezis
  • 1,631
  • 13
  • 20