【问题标题】:Python `os.remove` gets permission denied errorPython `os.remove` 获取权限被拒绝错误
【发布时间】:2020-01-02 07:42:53
【问题描述】:

我目前有一个 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'

【问题讨论】:

  • 没有回溯,不,我们不知道。
  • 你应该使用tempfile.TemporaryFile而不是mkstemp()
  • @tripleee 谢谢,我会添加回溯。

标签: python opencv


【解决方案1】:
_, 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)

而且你不必担心删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多