使用python正确编码文件路径 [英] Encode file path properly using python
本文介绍了使用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"
例如,以下文件路径将不会打开:foo,%20bar.mp3
For instance the following file path will not open: foo,%20bar.mp3
如果存在像逗号这样的字符,则应将其编码为:foo%2C%20bar.mp3
If characters like commas exist then it should be encoded as : foo%2C%20bar.mp3
谁能告诉我该怎么做?
推荐答案
您可能需要pathname2url
Python 2.x(文档)
Python 2.x (docs)
>>> from urllib import pathname2url
>>> pathname2url('foo, bar.mp3')
'foo%2C%20bar.mp3'
Python 3.x(文档 )
Python 3.x (docs)
>>> from urllib.request import pathname2url
>>> pathname2url('foo, bar.mp3')
'foo%2C%20bar.mp3'
这篇关于使用python正确编码文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文