如何避免使用 python-pptx 保存文件时出现 zipfile 错误 [英] How to avoid zipfile error with python-pptx saving files

查看:38
本文介绍了如何避免使用 python-pptx 保存文件时出现 zipfile 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python-pptx 包从一系列数据帧创建许多 .pptx 文件.所有这些都适用于添加幻灯片等,直到需要调用 prs.save() 其中prs"是演示文稿.这样做会导致 zipfile 错误:打开的句柄需要关闭.我对这个问题的历史做了一些研究(使用 python 2.6),但无法弄清楚为什么它会在 Python 3.7 中发生

I am using the python-pptx package to create a number of .pptx files from a series of dataframes. All works well with adding slides and such until it comes time to call prs.save() where "prs" is the Presentation. Doing so leads to a zipfile error re: open handles needing to be closed. I have done some research on the history of this problem (with python 2.6) but can't figure out why it's happening here with Python 3.7

[Errno 95] Operation not supported
Exception ignored in: <function ZipFile.__del__ at 0x7f15f2814e18>
Traceback (most recent call last):
  File "/usr/lib/python3.7/zipfile.py", line 1789, in __del__
    self.close()
  File "/usr/lib/python3.7/zipfile.py", line 1798, in close
    raise ValueError("Can't close the ZIP file while there is "
ValueError: Can't close the ZIP file while there is an open writing handle on it. Close the writing handle before closing the zip.

我在 Databricks 集群上运行它,在那里我从 pypi 安装了 python-pptx,所以我改变底层包的能力比我在本地机器上做的更有限/更复杂.

I am running this on a Databricks cluster where I installed python-pptx from pypi, so my ability to alter underlying packages is a bit more limited / complicated than if I was doing this on my local machine.

我也试过了

with open("new_ppt.pptx", "w") as f:
    prs = Presentation(f)

但这会导致文件不是 zip 类型的错误.

but this gives an error about the file not being of type zip.

在仍然能够创建 PPTX 文件的同时找到避免此错误的方法的可靠选择是什么?

What would be a solid option for finding a way to avoid this error while still being able to create the PPTX files?

谢谢!

推荐答案

如果它在本地工作(我想它会)但不在 Databricks 集群上,我会在那里寻找问题.也许它的文件系统与普通机器或其他东西不太一样.我知道有些环境不允许无限制地写入文件.

If it works locally (which I imagine it will) but not on the Databricks cluster, I would look there for the problem. Maybe it's filesystem isn't quite the same as a regular machine or something. I know some environments don't allow unrestricted writing of files.

您可以尝试的另一件事是写入 BytesIO 对象(内存中"文件)并查看是否有效.我不知道这是否能直接解决您的问题,但这将是一个有趣的额外数据点,用于推理正在发生的事情.

Another thing you can try is writing to a BytesIO object ("in-memory" file) and see if that works. I don't know if that directly solve your problem or not, but it would be an interesting additional datapoint for reasoning about what's happening.

from io import BytesIO

pptx_file = BytesIO()
prs.save(pptx_file)

# ---then maybe---
with open("deck.pptx", "wb") as f:
    f.write(pptx_file.getvalue())

这篇关于如何避免使用 python-pptx 保存文件时出现 zipfile 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆