'How can I make a data URL from a local file with Python?

I can read in a local file like so, but how can I now get the local file represented as a data url? I can't see any method for doing so.

This is a data url: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

import urllib.request
import random
import os

filename = urllib.request.pathname2url(random.choice(os.listdir('./sampledocuments')))
print(filename)

r = urllib.request.urlopen('file:///Users/myusername/sampledocuments/' + filename)


print(r)
print(r.info)
print(r.geturl)
print(dir(r))


Solution 1:[1]

Pretty straightforward: given mimetype and data,

import base64
...
f"data:{mimetype or ''};base64,{base64.b64encode(data).decode()}"

To get the data, you can modify your code as follows:

filename = random.choice(os.listdir('./sampledocuments'))
with open(filename, "rb") as f:
    data = f.read()

Set the mimetype if you know what it is, but it will work even if it's None (it just may not do what you want).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amadan