Search code examples
pythonurllocalfilepath

Convert Local File URL to File Path


I have a URL that points to a local file.

'file:///home/pi/Desktop/music/Radio%20Song.mp3'

I need to somehow convert this into a traditional file path, like the os module employs.

'/home/pi/Desktop/music/Radio Song.mp3'

Right now I'm hacking it with the replace() method.

path = file.replace('file://', '').replace('%20', ' ')

I've looked at the os module, and it doesn't seem to have support for this. I've searched various ways of phrasing it, and I can't seem to find an answer. Am I just ignorant of the terminology? What's the proper way to do this?


Solution

  • The following would work:

    from urllib.request import url2pathname
    from urllib.parse import urlparse
    
    p = urlparse('file:///home/pi/Desktop/music/Radio%20Song.mp3')
    file_path = url2pathname(p.path)
    print(file_path)
    

    (thanks to user @MillerTime correctly pointing out that the solution will not remove file:// without the urlparse)

    Output:

    /home/pi/Desktop/music/Radio Song.mp3
    

    urllib is a standard library, so no installation required.

    On a Windows machine, running just url2pathname would give you a valid file path right away, but it would be relative to the working directory of the script - e.g. running it from somewhere on D: drive:

    D:\home\pi\Desktop\music\Radio Song.mp3