Correctly encode file path with python

I am trying to open files by getting the path from the dictionary. Some file names contain commas (,) and other such characters that, when used, give "not such an error for the found file"

For example, the following file path will not be opened: foo,% 20bar.mp3

If symbols such as commas exist, it should be encoded as: foo% 2C% 20bar.mp3

Can someone tell me how to do this?

+7
source share
3 answers

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' 
+11
source

You can use urllib. The following example may need to be modified if you are using Python 3.x, but the general idea is the same:

 import urllib encoded_filename = urllib.quote(filename) f = open(encoded_filename) 
+2
source
 from urllib import pathname2url pathname2url('foo,bar.mp3') 
+2
source

All Articles