Reputation: 197
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?
Upvotes: 0
Views: 68
Reputation: 197
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
Upvotes: 0
Reputation: 12221
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.
Upvotes: 2