Attempting to delete files After unpacking python Zipfile

So there are a few posts about this, and I tried all the recommended solutions, but none of them seem to work. I am trying to delete a zip archive after I unzip it.

I tried os.remove, os.unlinkwith the help of the operator, witheverything! but i keep getting

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

Thank you very much in advance

def Unzip(f, password, foldername):
    '''
    This function unzips a file, based on parameters, 
    it will create folders and will overwrite files with the same 
    name if needed.
    '''

    if foldername != '':
        outpath = os.path.dirname(f) + '\\'+ foldername
        if not os.path.exists(outpath):
            os.mkdir(outpath)
    else:
        outpath = os.path.dirname(f)
        if not os.path.exists(outpath):
            os.mkdir(outpath)

    if password == '':
        z = zipfile.ZipFile(f)
        z.extractall(outpath)
        z.close()
        os.unlink(f)

    else:
        z = zipfile.ZipFile(f)
        z.extractall(outpath, None, password)
        z.close()
        os.unlink(f)

UPDATE, so I changed the code and this works:

    z = zipfile.ZipFile(f)
    z.extractall(outpath)
    z.close()
    del z
    os.unlink(f)
+4
source share
1 answer

This is caused by a bug ( issue 16183 ), which is now fixed in recent versions of Python 2 and 3. But as a workaround for earlier versions, pass in the object file, not the path:

with open(f, 'rb') as fileobj:
    z = zipfile.ZipFile(fileobj)
    z.extractall(outpath)
    z.close()
os.remove(f)
0
source

All Articles