Duke Dougal
Duke Dougal

Reputation: 26336

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))

Upvotes: 1

Views: 751

Answers (1)

Amadan
Amadan

Reputation: 198344

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

Upvotes: 4

Related Questions