Python Files Not Deleting After being Zipped

Question:

I’ve created a few functions which all work fine, when they are being outputed as an array, this has no issues and does not throw any error at all. For user ease, I’ve wanted to pack all these files into a ZIP folder, I’ve used the zipfile import in python to do this. However, I get an error when it comes to deleting the zip folder and the associated directory. The error I am getting is:
Application Command raised an exception: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'sent\mp_m_freemode_01-task_diff_001_[A-Z]_uni.ytd'

This is my python code:

for file in glob.glob('sent/*.ytd'):

            discord_prep = discord.File(file)
            uniforms.append(file)

            print("-- File to Send --")
            print(file)
            print("- File to Send Array -")
            print(uniforms)

        with zipfile.ZipFile(name + ".zip", mode="w") as archive:
            print("Making Archieve")

            for filename in uniforms:
                print(filename)
                archive.write(filename)

        archive.close()

        final_zip = discord.File(name + ".zip")

        await discord.asyncio.sleep(1)

        await ctx.send(
            file=final_zip
        )

        os.remove(name + ".zip")

        removing_files = glob.glob('sent/*.ytd')
        dir = os.listdir("sent/")

        if not len(dir) == 0:
            print("Clearing YTDs from Sent Folder")
            for i in removing_files:
                os.remove(i)

            print("All YTDs Removed")
        else:
            print("No YTDs to Clear")

        shutil.rmtree("sent/", ignore_errors=False, onerror=None)
        print("Sent Folder Deleted")

I tried and ensured that all my with open methods are closed and they are, but this error only occurs when I run the ZIP instructions, claiming it is being used in another device.

Asked By: Welshy1235

||

Answers:

In order to troubleshoot such issues on Windows, use SysInternals Process Explorer.

Go to the menu Find / Find Handle or DLL… or press Ctrl+F. Then enter the file name or a part of the file name. Don’t use wildcards. Process Explorer will then list all processes which access the file.

Example for mscoree

Answered By: Thomas Weller
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.