Nir Morgulis Nir Morgulis - 21 days ago 18
Python Question

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

I'm trying to use the following function:

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)


But I keep on getting the following error:

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


No other processes are running on my machine (as far as I know). If I leave out the
os.remove(fname)
function, then the code works well, but I don't want my temp folder to fill up with garbage.

Any idea what is keeping the image from being deleted?

Answer Source

Have you tried TemporaryFile() etc? Is there a particular reason why you want to use mkstemp()? This kind of thing might work

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

PS you could read the image data into an array something like described here 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))