Monday, April 21, 2025

Delete Multiple Files - Python

import os
import send2trash as s2t

target = 'c:\\Python38-64\\OLD-BACKUP\\'

for x in os.listdir(target):
    if x.endswith('.pyd'):
        s2t.send2trash(target + x)

This script uses the os module to list all files in a directory, and send2trash module to delete only files with the ".pyd" extension.

Here's how the code works:

  1. target variable is set to the directory path where the script will delete files with the ".pyd" extension.
  2. The os.listdir(target) function is used to get a list of all files in the directory.
  3. A for loop is used to iterate through each file in the list.
  4. An if statement checks if the file has the ".pyd" extension. If so, the send2trash() function is used to delete the file to the Recycle Bin.
  5. The file is deleted using send2trash() instead of os.remove() to send the file to the Recycle Bin instead of permanently deleting it.

This script is useful for deleting specific files from a directory without permanently deleting them.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...