Search code examples
pythonurl-encoding

Encode file path properly using python


I am trying to open files by getting the path from a dictionary. Some of the file names have commas (,) and other such characters which when used give a "no such file found error"

For instance the following file path will not open: foo,%20bar.mp3

If characters like commas exist then it should be encoded as : foo%2C%20bar.mp3

Can anyone tell me how to do this?


Solution

  • You may need pathname2url

    Python 2.x (docs)

    >>> from urllib import pathname2url 
    >>> pathname2url('foo, bar.mp3')
    'foo%2C%20bar.mp3'
    

    Python 3.x (docs)

    >>> from urllib.request import pathname2url
    >>> pathname2url('foo, bar.mp3')
    'foo%2C%20bar.mp3'