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

Question:

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?

Asked By: Amour Spirit

||

Answers:

Use os.path.normpath:

import os

os.path.normpath("file:///C:/Program%20Files/LibreOffice/program/../share/gallery/sounds/apert2.wav")

Output:

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

Note that the prefix is not correct anymore. So you may have to remove the "file:///" part first, then use normpath, then prepend the "file:///" part again.

Answered By: 9769953

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
Answered By: Amour Spirit
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.