[Python] Why am I getting "I/O operation on closed file" with PILLOW 3.1.0?

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to convert a tiff file into a PDF using Pillow and PyPDF. I was able to get this to work using an earlier version of Pillow, although I cannot which version.

    I recently upgraded to Pillow 3.1.0, and now I ran into issues. This is the previously working code.

    import os
    import traceback

    from PIL import Image
    from PyPDF2 import PdfFileReader, PdfFileMerger

    to_merge = []

    with Image.open('my_tif.tif') as img:
    seeker = 0

    while True:
    try:
    # temp file name for PDF
    img_pdf = 'temp_{}.pdf'.format(seeker)

    #seeks to next image with TIFF
    img.seek(seeker)

    # saves the image as a PDF
    img.save(img_pdf)

    seeker += 1
    to_merge.append(img_pdf)

    except Exception as err:
    traceback.print_exc()
    break

    merger = PdfFileMerger()
    for f in to_merge:
    merger.append(PdfFileReader(f))
    os.remove(f)
    merger.write('merged.pdf')


    Beforehand, it generated a PDF for each image within the tiff and then merged the PDFs together with no problem.

    After I upgraded to Pillow 3.1.0 it loops through all of the images, but then throws a ValueError on the final image.

    Traceback (most recent call last):
    File "C:/Code/Python/tiff_to_pdf.py", line 16, in <module>
    img.save(img_pdf)
    File "C:\Python27\lib\site-packages\PIL\Image.py", line 1675, in save
    save_handler(self, fp, filename)
    File "C:\Python27\lib\site-packages\PIL\PdfImagePlugin.py", line 155, in _save
    im.seek(pageNumber)
    File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 930, in seek
    self._seek(max(frame, 0)) # Questionable backwards compatibility.
    File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 956, in _seek
    self.fp.seek(self._frame_pos[frame])
    ValueError: I/O operation on closed file


    What would be the cause of the ValueError?

    Continue reading...

Compartilhe esta Página