[Python] Erro 'I/O operation on closed file' ao substituir imagens em arquivos Excel usando...

Discussão em 'Python' iniciado por Stack, Dezembro 9, 2024.

  1. Stack

    Stack Membro Participativo

    Estou desenvolvendo uma aplicação para trocar a logo do excel porém antes disso eu faço a comparação da imagem no qual quero substituir e a imagem nova se caso atender a referência ele deve trocar, quando vou alterar essa imagem e usar o método workbook.save(output_path) ele gera esse erro:

    Traceback (most recent call last): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\nbergmann.vscode\extensions\ms-python.debugpy-2024.12.0-win32-x64\bundled\libs\debugpy_vendored\pydevd_pydevd_bundle\pydevd_runpy.py", line 127, in _run_module_code
    _run_code(code, mod_globals, init_globals, mod_name, mod_spec, pkg_name, script_name) File "c:\Users\nbergmann.vscode\extensions\ms-python.debugpy-2024.12.0-win32-x64\bundled\libs\debugpy_vendored\pydevd_pydevd_bundle\pydevd_runpy.py", line 118, in _run_code exec(code, run_globals) File "c:\git\change-image-xlsx\change__image.py", line 117, in replace_image_in_xlsx('arquivo_duas_imagens.xlsx','img-old.png', 'new-image.png', 'arquivo_trocado.xlsx') File "c:\git\change-image-xlsx\change__image.py", line 50, in replace_image_in_xlsx workbook.save(output_path) File "C:\Users\nbergmann\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\openpyxl\workbook\workbook.py", line 386, in save save_workbook(self, filename) File "C:\Users\nbergmann\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\openpyxl\writer\excel.py", line 294, in save_workbook writer.save() File "C:\Users\nbergmann\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\openpyxl\writer\excel.py", line 275, in save self.write_data() File "C:\Users\nbergmann\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\openpyxl\writer\excel.py", line 79, in write_data self._write_images()

    img = _import_image(self.ref)

    ", line 16, in _import_image img = PILImage.open(img) ^^^^^^^^^^^^^^^^^^ File, line 3475, in open
    fp.seek(0) ValueError: I/O operation on closed file.

    import openpyxl
    import io
    import subprocess
    import os
    import logging
    from openpyxl.drawing.image import Image as ExcelImage
    from PIL import Image as PILImage
    from PIL import ImageChops, Image
    from io import BytesIO

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))


    def replace_image_in_xlsx(xlsx_path, old_image_path, new_image_path, output_path):
    workbook = openpyxl.load_workbook(xlsx_path)
    sheet = workbook.active
    substituir_palavra(sheet)
    images = sheet._images
    old_image = PILImage.open(old_image_path).convert('RGB')
    coordinates, image_sizes = getCoordinates(images)
    new_image = PILImage.open(new_image_path).convert('RGB')
    print(images)

    for i, coordinate in enumerate(coordinates):
    imagem_binaria = images._data()
    with open('imagem.png', 'wb') as f:
    f.write(imagem_binaria)
    f.close()
    img_stream = BytesIO(imagem_binaria)
    img_stream.seekable
    pil_image = PILImage.open(img_stream).convert('RGB') # aqui da dando ruim
    with Image.open(os.path.join(BASE_DIR, 'imagem.png')).convert('RGB') as f:
    # pil_image = PILImage.open(os.path.join(BASE_DIR, 'imagem.png')).convert('RGB')
    diff = ImageChops.difference(old_image, f)
    if diff.getbbox() is None:
    print("images are different")
    new_image_resized = new_image.resize((image_sizes[0], image_sizes[1]))
    new_image_resized.anchor = coordinate
    sheet.add_image(new_image_resized)



    workbook.save(output_path)
    print(f"Image replaced and saved as {output_path}")



    replace_image_in_xlsx('arquivo_duas_imagens.xlsx','img-old.png', 'new-image.png', 'arquivo_trocado.xlsx')

    Continue reading...

Compartilhe esta Página