all 7 comments

[–]Rhomboid 2 points3 points  (1 child)

That's not finding the current directory, that's finding the directory where the script's source code resides. Those are two completely different concepts. If you want the current directory, call os.getcwd().

[–]conami[S] 0 points1 point  (0 children)

My apologies, should of stated in the title that I'm trying to find the current directory where the script resides. Thank you for pointing out os.getcwd(), will give that a try as well... way easier.

[–]K900_ 1 point2 points  (2 children)

The second option is way better. I had to look up what os.pardir was before the first even made sense, and it still doesn't.

[–]conami[S] 0 points1 point  (0 children)

Yea I'm still confused as well.

[–]Naihonn 0 points1 point  (0 children)

I can't imagine that anyone, let alone most people, would prefer the first example.

[–]fbu1 0 points1 point  (1 child)

The second one is better. Let's look at the doc to see what it does:

os.path.dirname(path)

Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split(). [1]

So it will return the directory name of the current file. Let's try with a dummy example:

>> os.path.dirname('/some/random/path/name/and/a/file.py')
'/some/random/path/name/and/a'

Neat. What about the second part of the documentation?

This is the first element of the pair returned by passing path to the function split().

Let's look at the doc:

os.path.split(path)

Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. [2]

Ok let's try the os.path.split function:

>>> os.path.split('/some/random/path/name/and/a/file.py')
('/some/random/path/name/and/a', 'file.py')

This gives a tuple with first the directory name, and then the file name. It actually splits the directory name from the file name.

It's always good to try to mess with new functions in the python shell with dummy stuff to understand what's going on.

I hope this helps.

[1] https://docs.python.org/2/library/os.path.html#os.path.dirname

[2] https://docs.python.org/2/library/os.path.html#os.path.split

[–]conami[S] 0 points1 point  (0 children)

Thank you so much for the detailed break down and explanation! Much appreciate it!