2017-07-11 212 views
2

我嘗試使用下面的函數臨時圖像:PermissionError:[WinError 32]當試圖刪除

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

你試過禁用AV嗎? – kichik

+0

嘗試在提升的命令提示符下運行腳本。 –

回答

0

你試過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)) 
+0

謝謝你!像魔術般工作:) –