gpt4 book ai didi

python - 如何使用 pyscript 加载 zip 文件并保存到虚拟文件系统中

转载 作者:行者123 更新时间:2023-12-02 01:31:40 25 4
gpt4 key购买 nike

我正在尝试加载一个 zip 文件并将其保存在虚拟文件系统中,以便使用 pyscript 进行进一步处理。在此示例中,我旨在打开它并列出其内容。

据我所知:

请参阅下面的独立 html 代码,改编自 tutorials (感谢作者,顺便说一句)

它能够加载 Pyscript,让用户选择一个文件并加载它(尽管看起来格式不正确)。它创建一个虚拟 zip 文件并将其保存到虚拟文件,并列出内容。所有这些都是预先工作的,而且如果我将 process_file 函数指向那个虚拟 zip 文件,它确实会打开并列出它。

不工作的部分是当我通过按钮/文件选择器选择本地文件系统中任何有效的 zip 文件时,当将数据加载到 data 时它是文本 (utf-8)我得到这个错误:

File "/lib/python3.10/zipfile.py", line 1353, in _RealGetContents
raise BadZipFile("Bad magic number for central directory")
zipfile.BadZipFile: Bad magic number for central directory

我尝试保存到文件并加载它,而不是使用 BytesIO ,还尝试使用 ArrayBuffer 或 here 中的 Stream 的变体。我还尝试创建一个 FileReader 并使用 readAsBinaryString() 或 readAsText() 和各种转换,结果相同:要么它无法识别“魔数(Magic Number)”,要么我得到“不是 zip 文件”。当提供一些流或 arrayBuffer 时,我得到以下变化:

 TypeError: a bytes-like object is required, not 'pyodide.JsProxy' 

在这一点上,我怀疑有一些非常明显但我无法看到的令人尴尬的东西,因此,非常感谢任何新的眼睛和关于如何最好/简单地加载文件的建议 :)非常感谢。

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>Example</title>
</head>

<body>

<p>Example</p>
<br />
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br />
<br />
<div id="print_output"></div>
<br />
<p>File Content:</p>
<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:600px; resize:both">
<div id="content">
</div>
</div>

<py-script output="print_output">
import asyncio
import zipfile
from js import document, FileReader
from pyodide import create_proxy
import io

async def process_file(event):
fileList = event.target.files.to_py()
for f in fileList:
data= await f.text()
mf=io.BytesIO(bytes(data,'utf-8'))

with zipfile.ZipFile(mf,"r") as zf:
nl=zf.namelist()
nlf=" _ ".join(nl)
document.getElementById("content").innerHTML=nlf

def main():
# Create a Python proxy for the callback function
# process_file() is your function to process events from FileReader
file_event = create_proxy(process_file)
# Set the listener to the callback
e = document.getElementById("myfile")
e.addEventListener("change", file_event, False)

mf = io.BytesIO()
with zipfile.ZipFile(mf, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr('file1.txt', b"hi")
zf.writestr('file2.txt', str.encode("hi"))
zf.writestr('file3.txt', str.encode("hi",'utf-8'))
with open("a.txt.zip", "wb") as f: # use `wb` mode
f.write(mf.getvalue())

with zipfile.ZipFile("a.txt.zip", "r") as zf:
nl=zf.namelist()
nlf=" ".join(nl)

document.getElementById("content").innerHTML = nlf


main()
</py-script>

</body>

</html>

最佳答案

作为引用,根据 John Hanley 的回复(再次感谢!),这里是工作代码,添加了在虚拟文件系统中保存为二进制文件并从该文件加载它的演示:

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>File Example</title>
</head>

<body>

<p>Example</p>
<br />
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br />
<br />
<div id="print_output"></div>
<br />
<p>File Content:</p>
<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:600px; resize:both">
<div id="content">
</div>
</div>

<py-script output="print_output">
import asyncio
import zipfile
from js import document, FileReader, Uint8Array
from pyodide import create_proxy
import io

async def process_file(event):
fileList = event.target.files.to_py()
for f in fileList:
data = Uint8Array.new(await f.arrayBuffer())
mf = io.BytesIO(bytearray(data))
with zipfile.ZipFile(mf,"r") as zf:
nl=zf.namelist()
nlf=" ".join(nl)
document.getElementById("content").innerText+= "\n Test 2: reading file from local file system: "+f.name+" content:"+nlf
with open("b.zip","wb") as outb:
outb.write(bytearray(data))
with zipfile.ZipFile("b.zip", "r") as zf:
nl=zf.namelist()
nlf=" ".join(nl)
document.getElementById("content").innerText += "\n Test 3: reading the same file but first save it in virtual fs and read it: " + nlf



def main():
# Create a Python proxy for the callback function
# process_file() is your function to process events from FileReader
file_event = create_proxy(process_file)
# Set the listener to the callback
e = document.getElementById("myfile")
e.addEventListener("change", file_event, False)

mf = io.BytesIO()
with zipfile.ZipFile(mf, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr('file1.txt', b"hi")
zf.writestr('file2.txt', str.encode("hi"))
zf.writestr('file3.txt', str.encode("hi",'utf-8'))
with open("a.zip", "wb") as f: # use `wb` mode
f.write(mf.getvalue())

with zipfile.ZipFile("a.zip", "r") as zf:
nl=zf.namelist()
nlf=" ".join(nl)

document.getElementById("content").innerText = "Test 1: reading a dummy zip from virtual file system: " + nlf


main()
</py-script>

</body>

</html>

关于python - 如何使用 pyscript 加载 zip 文件并保存到虚拟文件系统中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73176562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com