[英]From pyscript, how can I access the file that I load from html?
This is the html input from which I load my file这是我加载文件的 html 输入
<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.出于安全原因,您应该创建一个文件侦听器并使用 pyodide 的 create_proxy 加载本地文件,然后异步处理该文件。 It looks like this
看起来像这样
index.html
索引.html
<!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.并且您的 main.py 脚本(我将其放在 index.html 的 py-script 节点的 src 属性中)创建代理并处理您选择的文件。
main.py
主文件
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.这样,浏览器等待输入文件元素上发生更改事件,然后在侦听器 (Process_File()) 中定义的文件事件激活异步处理文件。 More about it at: https://www.jhanley.com/pyscript-javascript-callbacks/
更多信息请访问: https://www.jhanley.com/pyscript-javascript-callbacks/
Try using pandas尝试使用 pandas
pandas.read_html()
https://pandas.pydata.org/docs/reference/api/pandas.read_html.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.或者,您可以获取 HTML 文件,并根据您想要的数据,将其发送到 csv,您可以从中轻松访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.