bogdan bogdan - 2 months ago 20x
Python Question

How can I normalize/collapse paths or URLs in Python in OS independent way?

I tried to use

in order to convert
but it doesn't work on Windows because it does convert the slash to backslash.


Here is how to do it

>>> import urlparse
>>> urlparse.urljoin("", "../..")
>>> urlparse.urljoin("", "../..")

Remember that urljoin consider a path/directory all until the last / - after this is the filename, if any.

Also, do not add a leading / to the second parameter, otherwise you will not get the expected result.

os.path module is platform dependent but for file paths using only slashes but not-URLs you could use posixpath,normpath.