Search code examples
pythonscipyfilesystemsfile-descriptor

Python: Close a file opened with scipy.misc.imread


In Python one can read in an image with scipy like so:

from scipy.misc import imread

img = imread('cats.jpg')

How can one close that opened file?


Solution

  • Okay, Scipy uses PIL under the cover, and PIL supports a with block syntax that automatically closes the file when the block is exited:

    from PIL import Image
    
    with Image.open('test.png') as test_image:
        do_things(test_image)