Is there a convenient way to map a file uri to os.path?

Gearoid Murphy picture Gearoid Murphy · May 12, 2011 · Viewed 12.4k times · Source

A subsystem which I have no control over insists on providing filesystem paths in the form of a uri. Is there a python module/function which can convert this path into the appropriate form expected by the filesystem in a platform independent manner?

Answer

Jakob Bowyer picture Jakob Bowyer · May 12, 2011

Use urllib.parse.urlparse to get the path from the URI:

import os
from urllib.parse import urlparse
p = urlparse('file://C:/test/doc.txt')
final_path = os.path.abspath(os.path.join(p.netloc, p.path))