Skip to content Skip to sidebar Skip to footer

How To Copy / Download File Created In Pyodide In Browser?

I managed to run Pyodide in browser. I created hello.txt file. But how can I access it. Pyodide https://github.com/iodide-project/pyodide/blob/master/docs/using_pyodide_from_javas

Solution 1:

Indeed pyodide operates in an in-memory (MEMFS) filesystem created by Emscripten. You can't directly write files to disk from pyodide since it's executed in the browser sandbox.

You can however, pass your file to JavaScript, create a Blob out of it and then download it. For instance, using,

let txt = pyodide.runPython(`                  
    with open('/test.txt', 'rt') as fh:
        txt = fh.read()
    txt
`);
const blob = newBlob([txt], {type : 'application/text'});
let url = window.URL.createObjectURL(blob);
window.location.assign(url);

It should have been also possible to do all of this from the Python side, using the type conversions included in pyodide, i.e.

from js import Blob, document
from js import window
  
withopen('/test.txt', 'rt') as fh:
    txt = fh.read()
    
blob = Blob.new([txt], {type : 'application/text'})
url = window.URL.createObjectURL(blob) 
window.location.assign(url)

however at present, this unfortunately doesn't work, as it depends on pyodide#788 being resolved first.

Solution 2:

I have modified the answer by rth. It will download file with the name of file.

let txt = pyodide.runPython(`                  
    with open('/test.txt', 'rt') as fh:
        txt = fh.read()
    txt
`);

const blob = newBlob([txt], {type : 'application/text'});
let url = window.URL.createObjectURL(blob);

var downloadLink = document.createElement("a");
downloadLink.href = url;
downloadLink.download = "test.txt";
document.body.appendChild(downloadLink);
downloadLink.click();

Post a Comment for "How To Copy / Download File Created In Pyodide In Browser?"