简体   繁体   中英

From pyscript, how can I access the file that I load from html?

This is the html input from which I load my file

<input type="file" id="fasta_1" accept=".fasta" class="form-control-file">

And this is the block of code from which I try to access the file but it doesn't work for me.

fasta_1 = Element("fasta_1")

document = fasta_1.element.files[0]
    print(document)
    #document = evt.target.files[0]
    #with open(document, "r") as f:
        #txtread = f.read()
        #print(document)

For security reasons you should create a file listener and use pyodide's create_proxy to load a local file and then process the file asynchronously. It looks like this

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href=pyscript.css" />
        <script defer src="pyscript.js"></script>       
        
<!--    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
        <script defer src="https://pyscript.net/alpha/pyscript.js" onerror=scriptLoadFailure('pyscr ipt.js')></script>      -->

<py-env>
paths:
    ./main.py
</py-env>
    </head>

    <body>
<py-script id="main" src="./main.py"></py-script>

    <input type="file" id="fasta_1" accept=".fasta" class="form-control-file">
    <div  id="outMsg"></div>
    </body>
</html>

And your main.py script (I put it in src attribute of py-script node of index.html) creating a proxy and processing the file that you choose.

import asyncio
from pyodide import create_proxy
#
#
def Setup_File_Listener():
    file_event = create_proxy(Process_File)
    e = document.getElementById("fasta_1")
    e.addEventListener("change", file_event, False)
#
#
async def Process_File(event):
    fileList = event.target.files.to_py()

    for f in fileList:
        data = await f.text()
        show_data(data)     #  OR do something else with the data
#
#        
def show_data(data):
    document.getElementById("outMsg").innerHTML = data

#   -----------------------------------------------------
Setup_File_Listener()

This way browser waits for a change event to happen on your input file element and then the file event defined in listener (Process_File()) activates asynchronous processing the file. More about it at: https://www.jhanley.com/pyscript-javascript-callbacks/

Try using pandas

pandas.read_html()

https://pandas.pydata.org/docs/reference/api/pandas.read_html.html

Alternatively, you could take the HTML file and depending on the data you want, send it to a csv, from which you can easily access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM