PermissionError: [WinError 32] when trying to delete a temporary image

PermissionError: [WinError 32] when trying to delete a temporary image

我正在尝试使用以下功能:

def image_from_url(url):
    """
    Read an image from a URL. Returns a numpy array with the pixel data.
    We write the image to a temporary file then read it back. Kinda gross.
    """
    try:
        f = urllib.request.urlopen(url)
        _, fname = tempfile.mkstemp()
        with open(fname, 'wb') as ff:
            ff.write(f.read())
        img = imread(fname)
        os.remove(fname)
        return img
    except urllib.error.URLError as e:
        print('URL Error: ', e.reason, url)
    except urllib.error.HTTPError as e:
        print('HTTP Error: ', e.code, url)

但我不断收到以下错误:

---> 67         os.remove(fname)
     68         return img
     69     except urllib.error.URLError as e:
     PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\Nir\AppData\Local\Temp\tmp8p_pmso5'

我的机器上 运行 没有其他进程(据我所知)。如果我省略 os.remove(fname) 函数,那么代码运行良好,但我不希望我的临时文件夹填满垃圾。

知道是什么阻止了图像被删除吗?

您尝试过 TemporaryFile() 等吗?您想使用 mkstemp() 有什么特别的原因吗?这种东西可能有用

with tempfile.NamedTemporaryFile('wb') as ff:
   ff.write(f.read())
   img = imread(ff.name)

PS 你可以将图像数据读入一个数组,就像这里描述的那样 How do I read image data from a URL in Python?

import urllib, io
from PIL import Image
import numpy as np

file = io.BytesIO(urllib.request.urlopen(URL).read()) # edit to work on py3
a = np.array(Image.open(file))

我和你有同样的错误。我已经一次又一次地卸载我的 anaconda,但仍然出现相同的错误。幸运的是,我发现这个网站(https://www.logilab.org/blogentry/17873)可以解决我的问题。 详细说明: 修改:

try:
    f = urllib.request.urlopen(url)
    _, fname = tempfile.mkstemp()
    with open(fname, 'wb') as ff:
        ff.write(f.read())
    img = imread(fname)
    os.remove(fname)
    return img

至:

try:
    f = urllib.request.urlopen(url)
    fd, fname = tempfile.mkstemp()
    with open(fname, 'wb') as ff:
        ff.write(f.read())
    img = imread(fname)
    os.close(fd)
    os.remove(fname)
    return img