Python Forum
Deleting Windows temp folder
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Deleting Windows temp folder
#1
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()
Reply
#2
Don't create the window if the folder is empty
Reply
#3
(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
Reply
#4
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,
Reply
#5
(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
Reply
#6
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
Reply
#7
Thanks for the input I will give it a try
Reply
#8
Well I found the solution to my problem it was quite easy and that I overlooked it
Thanks everyone for all your help
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question How to add Python folder in Windows Registry ? Touktouk 1 291 Feb-20-2024, 01:04 PM
Last Post: DeaD_EyE
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 578 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Rename files in a folder named using windows explorer hitoxman 3 766 Aug-02-2023, 04:08 PM
Last Post: deanhystad
  Compare filename with folder name and copy matching files into a particular folder shantanu97 2 4,539 Dec-18-2021, 09:32 PM
Last Post: Larz60+
  pyspark creating temp files in /tmp folder aliyesami 1 5,055 Oct-16-2021, 05:15 PM
Last Post: aliyesami
  Help with storing temp data for each day then recording min/max in app. trthskr4 3 2,452 Sep-10-2021, 10:51 PM
Last Post: trthskr4
  How to save Matplot chart to temp file? Morkus 2 4,562 Jun-12-2021, 10:52 AM
Last Post: Morkus
  Move file from one folder to another folder with timestamp added end of file shantanu97 0 2,492 Mar-22-2021, 10:59 AM
Last Post: shantanu97
  Python Cut/Copy paste file from folder to another folder rdDrp 4 5,096 Aug-19-2020, 12:40 PM
Last Post: rdDrp
  size of a windows folder metro17 1 1,798 Nov-03-2019, 06:20 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020