Use url as filename

Viewed 155

I have an url in python, and want to convert this to a suitable filename. I started with replacing "/" with "_" like this:

def encode_url(url):
    return url.replace("/", "_").replace(":", "#") + ".png"

I also wanted to be able to decode the filename to the original url:

def decode_filename(filename):
    n_url = ""
    for i in filename:
        if i == "#":
            n_url += ":"
        elif i == "_":
            n_url += "/"
        else:
            n_url += i
    return n_url

However, this will not work if the url is:

"https://example.com/example_example_example"

I need a encoding and decoding method that doesn't go over character limit that works on any given url. (If that exists)

The issue with base64 or hex encoding is that urls often exceed the character limit 255.

I am making a monitorer application in python that records changes of sites. I am comparing changes in images. I am storing the links in json in a config.json and then storing the images in a folder with the encode_url() method.

When the user deletes a link, it needs to be deleted from config.json and the folder containing the image. I am therefore needing the method to encode the url to be reversebale in order to delete the image file.

If there are better solutions than this, I would also accept this as an answer.

1 Answers
def encode_url(url):
    return url.replace("/", "$").replace(":", "#") + ".png"

def decode_filename(filename):
    return filename.replace('#',':').replace('$','_')
Related