[Image-SIG] Image.open should close file when it cannot identify image
fredrik at pythonware.com
Fri Oct 2 12:30:38 CEST 2009
On Fri, Oct 2, 2009 at 12:06 PM, Oliver Tonnhofer <olt at omniscale.de> wrote:
> I want to remove files that PIL can't open. But the following fails on
> Windows, because Image.open doesn't close the file.
Unless you hang on to the image object, Python will close things when
the image object itself goes away.
Your workaround doesn't handle anything that might happen during open;
to force the file to be closed if it cannot be fully read no matter
what caused the problem, I'd recommend doing something like:
file = open(filename, "rb")
im = Image.open(file)
file.close() # force close
... process unreadable file ...
... process image ...
> import os
> import Image
> f = open('test.test', 'w')
> results in:
> WindowsError: [Error 32] The process cannot access the file because it is
> used by another process: 'test.test'
> Below is a simple fix.
> PS: please cc me on replies to the list.
> --- PIL/Image.py.orig 2009-10-02 12:02:26.000000000 +0200
> +++ PIL/Image.py 2009-10-02 12:03:12.000000000 +0200
> @@ -1913,6 +1913,9 @@
> except (SyntaxError, IndexError, TypeError):
> + if filename:
> + fp.close()
> raise IOError("cannot identify image file")
> Image-SIG maillist - Image-SIG at python.org
More information about the Image-SIG