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?
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'
from urllib import pathname2url
pathname2url('foo,bar.mp3')
You can use urllib. The following example might need to be changed if you use Python 3.x, but the general idea is the same:
import urllib
encoded_filename = urllib.quote(filename)
f = open(encoded_filename)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With