7

As a response to this answer to a previous question of mine, I wrote the following short program to try and reproduce the problem.

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

This produced two pptx files.

The first, test.pptx, contained a single slide with the "Title Slide" layout and containing the string "asdf". The file size was 28 KB.

The second, bytes_test.pptx, when opened in PowerPoint, showed only a large grey box that said "Click to add first slide". The file size was 0.

Running on Windows 10 with Anaconda Python 3.6.1 and python-pptx 0.6.6

Why does this happen?

4

1 回答 1

5

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

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

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

让我们知道你是怎么做的,我们会从那里开始的。

于 2017-10-27T19:23:30.017 回答