Search code examples
pythonurirelative-path

How to convert a URI containing partial relative path like '/../' in the middle?


LibreOffice API object is returning a URI path that contains relative path in the middle of the string, like:

file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav

How to convert this to the absolute like:

file:///C:/Program%20Files/LibreOffice/share/gallery/sounds/apert2.wav

How would I convert this?


Solution

  • Ok so Window convert forward slashes to back slash in this context.

    Here is my final solution.

    def uri_absolute(uri: str) -> str:
        uri_re = r"^(file:(?:/*))"
        # converts
        # file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav
        # to
        # file:///C:/Program%20Files/LibreOffice/share/gallery/sounds/apert2.wav
        result = os.path.normpath(uri)
        # window will use back slash so convert to forward slash
        result = result.replace("\\", "/")
        # result may now start with file:/ and not file:///
    
        # add proper file:/// again
        result = re.sub(uri_re, "file:///", result, 1)
        return result