我需要将 Plotly 图形保存为 zip 文件中的图像。我还需要将我的程序生成的一些文本作为文本文件存储在 zip 文件中。这是我的尝试:
import io
import zipfile
import plotly.express as px
import kaleido
#write texts to stringIO
s = io.StringIO()
texts = ['foo','bar']
newline = '\n'
for text in texts:
s.write(text)
s.write(newline)
#create sample plotly figure
long_df = px.data.medals_long()
fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input")
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, mode="w") as zf:
fig_png = fig.to_image(format="png") # kaleido library
buf = io.BytesIO(fig_png)
zf.writestr('barplot.png', buf.getvalue()) #write plot as png file
zf.writestr('text.txt', s.getvalue()) #write texts as text file
with open("a.zip", "wb") as f:
f.write(zip_buffer.getbuffer())
它确实创建了一个 zip 文件,但运行可能需要 5 秒。我是在错误地实施它还是就是这样?有没有更好的方法请指教