Python Forum
Deleting Windows temp folder - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Deleting Windows temp folder (/thread-41867.html)



Deleting Windows temp folder - Raysz - Mar-30-2024

I'm hoping somebody here can help me figure this out

Basically what I'm trying to do is delete everything in the Windows 10 temp folder
if there is an item or more in the folder this program works perfectly

What it supposed to do is delete all the items and then close the top level window
which it does

The problem is if the folder is empty
the top level window will not close
I'm having a difficult time figuring why this is happening

ps
I'm also using messagebox.askyesno()
if you select no it will close the top level window
every time whether the folder is empty or not

If you select yes hence I have the problem
again if the folder is empty the top level window will not close
if the folder has items in it the top level window will close

Any help would be greatly appreciated
I am missing something here I just can't see it

Here is a sample of my script


def windows_temp_data():
    # temp cleans Windows temp folder
    top = Toplevel()
    top.geometry("677x386")  # Size of the window
    top.title('Command Prompt In Tkinter')

    # Listbox -shows program file description-
    label_header = Label(top, text='Program information', font=('Arial bold', 13))
    label_header.place(x=150, y=10)
    my_listbox = tk.Listbox(top, bg='black', fg='white', font=('Arial Bold', 13))
    my_listbox.pack(expand=True, fill=tk.BOTH)  # x=justify left to right

    scrollbar = Scrollbar(my_listbox)
    scrollbar.pack(side=RIGHT, fill=Y)
    my_listbox.config(yscrollcommand=scrollbar.set)
    scrollbar.config(command=my_listbox.yview)

    # username = getpass.getuser()
    # current location of the users temp folder
    temp_dir_wtd = f'C:\\Windows\\Temp'
    files_wtd = os.listdir(temp_dir_wtd)
    for file_wtd in files_wtd:
        filepath = os.path.join(temp_dir_wtd, file_wtd)
        my_listbox.insert(END, file_wtd)
    response = messagebox.askyesno('Maintenance', 'Would you like to remove these files')
    if response is True:
        print('hi')
        for file_wtd in files_wtd:
            filepath = os.path.join(temp_dir_wtd, file_wtd)
            try:
                if os.path.isfile(filepath):
                    os.unlink(filepath)
                elif os.path.isdir(filepath):
                    shutil.rmtree(filepath)
                    top.after(2000, lambda: my_listbox.insert(END, filepath))
                    my_listbox.delete(0, END)
                    top.after(2000, top.destroy)
            except (Exception,):
                print('ko')
                top.after(2000, lambda: my_listbox.insert(END, filepath))
                my_listbox.delete(0, END)
                top.after(2000, top.destroy)

    elif response is False:
        messagebox.showinfo('information', 'very well I will leave it alone')
        top.after(1000, top.destroy)

    top.mainloop()



RE: Deleting Windows temp folder - deanhystad - Mar-30-2024

Don't create the window if the folder is empty


RE: Deleting Windows temp folder - Raysz - Mar-31-2024

(Mar-30-2024, 06:52 PM)deanhystad Wrote: Don't create the window if the folder is empty

Okay I'm not sure I understand what you're trying to say

if I run the program enters items in the folder it will delete them and then close the top level window
if I try and do it again now the folder is empty it won't close the window so how do I fix that


RE: Deleting Windows temp folder - deanhystad - Mar-31-2024

I would check if the folsed is enpty. If the folder is not empty, create the window,, else don't create the window. It is silly asking the user if they want to clean up the temp folder when there is nothing to clean up,


RE: Deleting Windows temp folder - Raysz - Mar-31-2024

(Mar-31-2024, 12:32 PM)deanhystad Wrote: I would check if the folsed is enpty. If the folder is not empty, create the window,, else don't create the window. It is silly asking the user if they want to clean up the temp folder when there is nothing to clean up,

Okay the folder is empty that's the problem for the bug in this procedure
since the folder is empty the program will not close the window


RE: Deleting Windows temp folder - deanhystad - Apr-01-2024

Modify the function so it first checks if the folder is empty. If the folder is empty it should not create the window at all. Don't ask the user if they want to delete temporary files when there are no temporary files.

I would split the task into two parts: make a custom dialog to get user input and write a function that uses the dialog.
class DeleteFilesDialog(tk.Toplevel):
    """File delete dialog
    Displays files in list and buttons to delete the files or cancel the operation.
    """
    def __init__(self, files, prompt=None, title="Delete Files", ok="Yes", cancel="No", rows=10):
        super().__init__()
        self.title(title)
        self.protocol("WM_DELETE_WINDOW", self.quit)

        if prompt:
            tk.Label(self, text=prompt).pack()

        frame = tk.Frame(self)
        frame.pack(expand=True, fill=tk.BOTH)
        height = min(len(files), rows)
        width = max(len(file) for file in files)
        display = tk.Listbox(frame, width=width, height=height, bg=self["background"], bd=0)
        scrollbar = tk.Scrollbar(frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        display.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=display.yview)
        display.pack(expand=True, fill=tk.BOTH, padx=10)

        frame = tk.Frame(self)
        frame.pack(expand=True, fill=tk.X)
        button = tk.Button(frame, text=ok, command=self.ok)
        button.pack(padx=10, pady=10, side=tk.LEFT, expand=True, fill=tk.BOTH)
        button = tk.Button(frame, text=cancel, command=self.quit)
        button.pack(padx=10, pady=10, side=tk.LEFT, expand=True, fill=tk.BOTH)

        for file in files:
            display.insert(tk.END, file)
        self._result = False
        self.mainloop()
        self.destroy()

    def ok(self):
        """Callback when Ok button pressed."""
        self._result = True
        self.quit()

    @property
    def result(self):
        """Return True of Ok button pressed, else False"""
        return self._result


def delete_temp_files():
    """Clean out temp folder."""
    temp = r"C:\Windows\Temp"
    files = [os.path.join(temp, file) for file in os.listdir(temp)]

    # If files found, prompt user to delete.
    if files and DeleteFilesDialog(files, "Delete these files?").result:
        for file in files:
            try:
                if os.path.isfile(file):
                    os.unlink(file)
                elif os.path.isdir(file):
                    shutil.rmtree(file)
            except Exception:
                pass

        # Notify user if some files not deleted.
        if os.listdir(temp):
            messagebox.showwarning("Warning", "Not all files were deleted.")
The main problem with your code is that if the user selects "Yes" in the message box when there are no files, the window is never destroyed. The commands to destroy the window are inside the for loop, and the for loop never executes if there are no files to delete. The destroy command should be outside the for loop.
    if response is True:
        print('hi')
        for file_wtd in files_wtd:
            filepath = os.path.join(temp_dir_wtd, file_wtd)
            try:
                if os.path.isfile(filepath):
                    os.unlink(filepath)
                elif os.path.isdir(filepath):
                    shutil.rmtree(filepath)
            except Exception:
                pass
        top.after(2000, top.destroy)  # Should not be in for loop



RE: Deleting Windows temp folder - Raysz - Apr-01-2024

Thanks for the input I will give it a try


RE: Deleting Windows temp folder - Raysz - Apr-02-2024

Well I found the solution to my problem it was quite easy and that I overlooked it
Thanks everyone for all your help