为什么将演示文稿保存到类似文件的对象会产生空白演示文稿?

Why does saving a presentation to a file-like object produce a blank presentation?

作为对 this answer 我之前的一个问题的回应,我编写了以下短程序来尝试重现该问题。

from pptx import Presentation
from io import BytesIO

p = Presentation()
slide = p.slides.add_slide(p.slide_layouts[0])
slide.shapes[0].text = 'asdf'

p.save('test.pptx')

out = BytesIO()
p.save(out)

out_file = open('bytes_test.pptx', 'wb', buffering=0)
out_file.write(out.read())
out_file.close()

这产生了两个 pptx 文件。

第一个 test.pptx 包含一张幻灯片,其布局为 "Title Slide",并包含字符串 "asdf"。文件大小为 28 KB。

第二个,bytes_test.pptx,在 PowerPoint 中打开时,只显示一个大灰色框,上面写着 "Click to add first slide"。文件大小为 0。

运行 在 Windows 10 上使用 Anaconda Python 3.6.1 和 python-pptx 0.6.6

为什么会这样?

好吧,我能想到一些事情,这可能需要一些来回。

首先,我会尝试使用 out.getvalue() 而不是 out.read()。我一直都是这样做的,它记录的行为是获取流的全部内容。

如果这不起作用,我会在 out.read() 调用之前添加 out.flush()out.seek(0)BytesIO 是一个缓冲输出流,在 read() 调用之前,可能有一些缓冲数据没有写入流中。另外,我希望 read() 从当前光标位置开始工作,seek(0) 调用会将其重置为文件的开头。

让我们知道您的处理方式,我们将从那里着手。