Encode file path properly using python

孤者浪人 提交于 2019-12-08 16:23:58

问题


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?


回答1:


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'



回答2:


from urllib import pathname2url
pathname2url('foo,bar.mp3')



回答3:


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)


来源:https://stackoverflow.com/questions/5960751/encode-file-path-properly-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!