开发者

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.开发者_Python百科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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜