views:

136

answers:

3

I tried to use os.normpath in order to convert http://example.com/a/b/c/../ to http://example.com/a/b/ but it doesn't work on Windows because it does convert the slash to backslash.

+5  A: 

Here is how to do it

import urlparse

# this will get ftp://domain.com/a/b/
urlparse.urljoin("ftp://domain.com/a/b/c/d/", "/../..")

# this will get ftp://domain.com/a/b/
urlparse.urljoin("ftp://domain.com/a/b/c/d/e.txt", "/../..")

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

Also, do not forget to 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.

Sorin Sbarnea
+1  A: 

Python's URL handling is in urlparse.

Ignacio Vazquez-Abrams
A: 

adopted from os module " - os.path is one of the modules posixpath, or ntpath", in your case explicitly using posixpath.

   >>> import posixpath
    >>> posixpath.normpath("/a/b/../c")
    '/a/c'
    >>> 
Dyno Fu