On Fri, Oct 2, 2009 at 12:06 PM, Oliver Tonnhofer <o...@omniscale.de> wrote:
> Hi,
>
> 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")
    try:
        im = Image.open(file)
        im.load()
    except StandardError:
        file.close() # force close
        ... process unreadable file ...
    else:
        ... process image ...

</F>




>
> ----
> import os
> import Image
> try:
>    f = open('test.test', 'w')
>    f.close()
>    Image.open('test.test')
> finally:
>    os.remove('test.test')
> ----
> results in:
> WindowsError: [Error 32] The process cannot access the file because it is
> being
> used by another process: 'test.test'
>
>
> Below is a simple fix.
>
> Regards,
> Oliver
>
> 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):
>             pass
>
> +    if filename:
> +        fp.close()
> +
>     raise IOError("cannot identify image file")
>
>  #
>
> _______________________________________________
> Image-SIG maillist  -  image-...@python.org
> http://mail.python.org/mailman/listinfo/image-sig
>
_______________________________________________
Image-SIG maillist  -  Image-SIG@python.org
http://mail.python.org/mailman/listinfo/image-sig

Reply via email to