Python`os.remove`获取权限被拒绝错误

时间:2019-08-29 05:00:50

标签: python opencv

我目前有一个Python函数,可以读取图像文件并输出图像,然后在将os.remove函数与临时文件一起使用时将其删除。

但是,当我尝试使用os.remove函数时,出现权限拒绝错误,指出该文件仍在使用中。我已经尝试遵循this answer的建议,但是效果不佳(或者我没有正确实现)。

这是有问题的代码:

def image_from_url(url):
    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)

我尝试将img = imread(fname)行放在with open块中,但这没用。

有人对问题可能有想法吗?谢谢。

编辑

更具体地说,此功能正在由另一个脚本调用:

# Sample a minibatch and show the images and captions
batch_size = 3

captions, features, urls = coco_minibatch(data, batch_size=batch_size)
for i, (caption, url) in enumerate(zip(captions, urls)):
    plt.imshow(image_from_url(url))
    plt.axis('off')
    caption_str = decode_captions(caption, data['idx_to_word'])
    plt.title(caption_str)
    plt.show()

您可以看到image_from_url函数在for循环的第一行中被调用。

错误回溯如下:

---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
<ipython-input-5-fe0df6739091> in <module>
      4 captions, features, urls = sample_coco_minibatch(data, batch_size=batch_size)
      5 for i, (caption, url) in enumerate(zip(captions, urls)):
----> 6     plt.imshow(image_from_url(url))
      7     plt.axis('off')
      8     caption_str = decode_captions(caption, data['idx_to_word'])

~\directory\image_utils.py in image_from_url(url)
     73 
     74         img = imread(fname)
---> 75         os.remove(fname)
     76 
     77         return img

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\JohnDoe\\AppData\\Local\\Temp\\tmp_lg3agzf'

1 个答案:

答案 0 :(得分:0)

_, fname = tempfile.mkstemp()

打开新创建的临时文件,并返回打开的文件和名称作为元组。明显的错误解决方案是做

    temporary_file, fname = tempfile.mkstemp()

    with temporary_file as ff:
        ff.write(f.read())
        img = imread(fname)

    os.remove(fname)

正确的解决方案是不使用mkstemp而是使用NamedTemporaryFile

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

您不必担心删除。