How to save a presentation to a file-like object in Python 3

Python 3 replaced StringIO.StringIOwith io.StringIO. I was able to successfully save the presentations using the former, but it does not seem to work for the latter.

from pptx import Presentation
from io import StringIO

presentation = Presentation('presentation.pptx')
output = StringIO()
presentation.save(output)

The above code gives:

Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\site-packages\pptx\presentation.py", line 46, in save self.part.save(file) File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\site-packages\pptx\parts\presentation.py", line 118, in save self.package.save(path_or_stream) File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\site-packages\pptx\opc\package.py", line 166, in save PackageWriter.write(pkg_file, self.rels, self.parts) File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\site-packages\pptx\opc\pkgwriter.py", line 33, in write PackageWriter._write_content_types_stream(phys_writer, parts) File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\site-packages\pptx\opc\pkgwriter.py", line 47, in _write_content_types_stream phys_writer.write(CONTENT_TYPES_URI, content_types_blob) File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\site-packages\pptx\opc\phys_pkg.py", line 156, in write self._zipf.writestr(pack_uri.membername, blob) File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\zipfile.py", line 1645, in writestr with self.open(zinfo, mode='w') as dest: File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\zipfile.py", line 1349, in open return self._open_to_write(zinfo, force_zip64=force_zip64) File "C:\Users\mgplante\AppData\Local\Continuum\Anaconda2\envs\ppt_gen\lib\zipfile.py", line 1462, in _open_to_write self.fp.write(zinfo.FileHeader(zip64)) TypeError: string argument expected, got 'bytes'

Is there a way to save the presentation for a file object in Python 3, or will I have to use Python 2 for this project?

+4
source share
2 answers

How about BytesIO()?

from pptx import Presentation
from io import BytesIO

presentation = Presentation('presentation.pptx')
output = BytesIO()
presentation.save(output)

This fixes the error at a minimum.

+2
source

Hannu's answer is absolutely right, and this is exactly the code that is used to test this behavior in the test suite for python-pptx:

stream = BytesIO()
presentation.save(stream)

https://github.com/scanny/python-pptx/blob/master/features/steps/presentation.py#L105

, - . , , : " ?" SO, , .

, - , , - , , . , , , .

, , , :

prs = Presentation()
output = BytesIO()
prs.save(output)

, , , , , , , , .

, :)

+1

Source: https://habr.com/ru/post/1688306/


All Articles