PermissionError: [WinError 32] The process cannot access the file because it is being used by another process

前端 未结 4 455
南笙
南笙 2020-11-27 07:39

My code is for a script that looks at a folder and deletes images that are under a resolution of 1920x1080. The problem I am having is that when my code runs;



        
相关标签:
4条回答
  • 2020-11-27 07:52

    I was running into the same problem, but the error was intermittent. If you are coding your file open/close correctly and still running into this error, make sure you are not synching the files with Dropbox, Google Drive, etc. I paused Dropbox and I no longer see the error.

    0 讨论(0)
  • 2020-11-27 08:01

    This is basically permission error, you just need to close the file before removing it. After getting the image size info, close the image with

    im.close()
    
    0 讨论(0)
  • 2020-11-27 08:09

    I also had the issue, in windows [WinError 32]

    Solved by changing:

    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
    

    into:

    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
    

    As found here: https://no.coredump.biz/questions/45042466/permissionerror-winerror-32-when-trying-to-delete-a-temporary-image

    0 讨论(0)
  • 2020-11-27 08:19

    Your process is the one that has the file open (via im still existing). You need to close it first before deleting it.

    I don't know if PIL supports with contexts, but if it did:

    import os
    from PIL import Image
    
    while True:    
        img_dir = r"C:\Users\Harold\Google Drive\wallpapers"
        for filename in os.listdir(img_dir):
            filepath = os.path.join(img_dir, filename)
            with Image.open(filepath) as im:
                x, y = im.size
            totalsize = x*y
            if totalsize < 2073600:
                os.remove(filepath)
    

    This will make sure to delete im (and close the file) before you get to os.remove.

    If it doesn't you might want to check out Pillow, since PIL development is pretty much dead.

    0 讨论(0)
提交回复
热议问题