PermissionError:[WinError 32]尝试删除临时图像时

时间:2017-07-11 18:51:24

标签: python permissions imread

我试图使用以下功能:

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)函数,那么代码运行良好,但我不想让我的临时文件夹填满垃圾。

知道是什么让图片不被删除?

2 个答案:

答案 0 :(得分:0)

您是否尝试过TemporaryFile()等?是否有特殊原因要使用mkstemp()?这种事情可能会起作用

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))

PS你可以将图像数据读入一个像How do I read image data from a URL in Python?

这样描述的数组中
{{1}}

答案 1 :(得分:0)

我也遇到同样的错误。我已经一次又一次卸载了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