2

Currently I do not understand, why pythons os.path.dirname behave like it does.

Let's assume I have the following script:

# Not part of the script, just for the current sample
__file__ = 'C:\\Python\\Test\\test.py'

Then I try to get the absolute path to the following directory: C:\\Python\\doc\\py

With this code:

base_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)) + '\\..\\doc\\py\\')

But why does the method os.path.dirname does not resolve the path, and print out (print (base_path):

C:\Python\Test\..\doc\py

I've expected the method to resolve the path to:

C:\Python\Test\doc\py

I just know this behaviour from the .NET Framework, that getting directory paths will always resolve the complete path and remove directory changes with ..\\. What do I have in Python for possibilities to do this?

2 Answers 2

3

Look into os.path.normpath

Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes.

The reason os.path.dirname works the way it does is because it's not very smart - it even work for URLs!

os.path.dirname("http://www.google.com/test")  # outputs http://www.google.com

It simply chops off anything after the last slash. It doesn't look at anything before the last slash, so it doesn't care if you have /../ in there somewhere.

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

1 Comment

Perfect, thank you. The only thing that was additionaly wrong was, i had to change: ) + '..\\doc\\py\\') to ) + '\\..\\doc\\py\\')
2

os.path.normpath() will return a normalized path, with all references to the current or parent directory removed or replaced appropriately.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.