Skip to content

Image.save() does not close file pointer #2760

@rustyis

Description

@rustyis

What did you do?

I'm modifying a large number of single-page tiffs as NumPy arrays and saving each to file individually via Image.fromarray. For example:

for src_path in img_list:
    np_array = cv2.imread(src_path, 0)
    with Image.fromarray(np_array) as img:
        img = img.convert('1')
        img.save(dst_path, format='tiff')

What did you expect to happen?

I expected the full list of images to be read into arrays in turn by OpenCV & NumPy and saved as TIFFs by Pillow.

What actually happened?

After exactly 1020 successful iterations, I get the following error:

Converting 1021 of 5173: bort_005.png
Traceback (most recent call last):
  File "C:\TestEnv\Pillowtest\test.py", line 94, in <module>
    main(sys.argv[1:])
  File "C:\TestEnv\Pillowtest\test.py", line 39, in main
    img.save(dst_path, format='tiff')
  File "C:\Python34\lib\site-packages\PIL\Image.py", line 1893, in save
    save_handler(self, fp, filename)
  File "C:\Python34\lib\site-packages\PIL\TiffImagePlugin.py", line 1430, in _save
    _fp = os.dup(fp.fileno())
OSError: [Errno 24] Too many open files

Press enter to continue.

What versions of Pillow and Python are you using?

Python v3.4.4 (x64) on Windows 7
Pillow 4.2.1

What have you tried?

I have tried enclosing img.save() in a context manager, as well as explicitly closing the file pointer (if that's even possible or relevant here?), e.g.

with open(dst_path, 'wb') as image_file:
    img.save(image_file, format='tiff')
    img.close()
    image_file.close()

I have also seen and reviewed the following issues, and have not been able to successfully implement their workarounds. This case seems to be different due to the lack of calling either Image.open() or Image.load().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions