Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.mp3

Can anyone tell me how to do this?

like image 387
bcosynot Avatar asked May 11 '11 07:05

bcosynot


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'
like image 79
neurino Avatar answered Sep 27 '22 16:09

neurino


from urllib import pathname2url
pathname2url('foo,bar.mp3')
like image 24
Riccardo Galli Avatar answered Sep 27 '22 18:09

Riccardo Galli


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)
like image 25
Boaz Yaniv Avatar answered Sep 27 '22 18:09

Boaz Yaniv