如何使用 python-pptx 保存文件避免 zipfile 错误

How to avoid zipfile error with python-pptx saving files

我正在使用 python-pptx 包从一系列数据帧创建大量 .pptx 文件。所有这些都可以很好地添加幻灯片等,直到需要调用 prs.save(),其中“prs”是演示文稿。这样做会导致 zipfile 错误 re: open handles needed to be closed。我已经对这个问题的历史做了一些研究(python 2.6),但无法弄清楚为什么 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,所以我改变底层包的能力比我这样做更有限/更复杂在我的本地机器上。

另外,我试过了

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

但这给出了关于文件不是 zip 类型的错误。

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

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

您可以尝试的另一件事是写入 BytesIO 对象("in-memory" 文件)并查看是否可行。我不知道这是否能直接解决您的问题,但这将是一个有趣的附加数据点,用于推理正在发生的事情。

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())