Monday, April 21, 2025

Delete All Files with Specific Extension in a Folder

import os, time

target = 'c:\\Python38-64\\SOME-FOLDER\\'

for x in os.listdir(target):
    if x.endswith('.pyd'):
        print('Deleting File: ' + x)
        os.unlink(target + x)
        time.sleep(2)

This Python code imports the "os" and "time" modules.

It assigns a string path 'c:\Python38-64\SOME-FOLDER\' to the variable "target". This variable represents the path of a directory that contains files.

The code then uses a "for" loop to iterate over the list of items returned by the "os.listdir" method, which returns a list of all files and directories in the directory specified by "target". For each item in the list, the code checks if the file has a '.pyd' extension using the "endswith" method. If it does, the code prints a message indicating that the file is being deleted, and then deletes the file using the "os.unlink" method, passing in the full path of the file (which is constructed by concatenating the "target" variable with the file name, separated by a backslash).

After deleting the file, the code sleeps for 2 seconds using the "time.sleep" method, to provide a delay before proceeding to the next file.

So, in essence, the code is trying to delete all files in the directory specified by "target" that have a '.pyd' extension. It does this by iterating over all the files and directories in that directory using the "os.listdir" method, checking if each file has a '.pyd' extension, and if so, deleting the file using the "os.unlink" method with a delay of 2 seconds between deletions.

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 .  ...