Monday, April 21, 2025

Recursively Search for Files with a Specific Extension

import os

target = 'c:\\Python38-64'

report = open('specific-ext.txt', 'w')

for root, dirname, files in os.walk(target):
    for x in files:
        if x.endswith('.txt'):
            report.write(root + '\\' + x + '\n')

report.close()

This code walks through the directory tree rooted at c:\\Python38-64, and for each file found with a .txt extension, it writes the full path of the file (composed of the root directory and the filename) to a file named specific-ext.txt.

First, it opens a new file named specific-ext.txt in write mode using the open() function. Then it loops through each directory, subdirectory, and file within the root directory using the os.walk() function. For each file found, it checks if its extension is .txt using the endswith() method of strings. If the extension is .txt, it writes the full path of the file to the specific-ext.txt file using the write() method of the file object. Finally, it closes the file using the close() method.

Export List of Deleted Files to .TXT File

import os
import send2trash as s2t

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

file = open('removed-files.txt', 'w')

for x in os.listdir(target):
    if x.endswith('.dll'):
        s2t.send2trash(target + x)
        file.write(target + x + '\n')

file.close()

This script uses the send2trash module to send files with the .dll extension in the c:\Python38-64\OLD-BACKUP\ directory to the trash. The file paths of the deleted files are also written to a removed-files.txt file in write mode.

Here's a breakdown of the script:

  1. import os and import send2trash as s2t import the necessary modules for the script.
  2. target = 'c:\\Python38-64\\OLD-BACKUP\\' sets the target directory where the script will look for files with the .dll extension.
  3. file = open('removed-files.txt', 'w') opens a new file called removed-files.txt in write mode.
  4. for x in os.listdir(target): loops through the files in the target directory.
  5. if x.endswith('.dll'): checks if the current file has the .dll extension.
  6. s2t.send2trash(target + x) sends the file to the trash.
  7. file.write(target + x + '\n') writes the file path of the deleted file to the removed-files.txt file, followed by a newline character (\n).
  8. file.close() closes the removed-files.txt file.

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.

Send File to Recycle Bin with Python - send2trash

send2trash is a Python module that provides a cross-platform way of sending files and directories to the operating system's trash or recycle bin, rather than deleting them permanently.

The module provides a simple function send2trash.send2trash() that takes a file or directory path as input and sends it to the operating system's trash or recycle bin, depending on the platform. 

C:\Users\user>pip install send2trash
Collecting send2trash
  Using cached Send2Trash-1.5.0-py3-none-any.whl (12 kB)
Installing collected packages: send2trash
Successfully installed send2trash-1.5.0

C:\Users\user>

The command pip install send2trash installs the send2trash Python module, which provides a cross-platform way of sending files and directories to the operating system's trash or recycle bin, rather than deleting them permanently.

If you run this command in your command prompt, it should start the installation process of send2trash

import send2trash as s2t

try:
    s2t.send2trash('some-report.txt')    
except:
    print('Cant\'t delete that file')

This code use the send2trash module to attempt to send a file named 'some-report.txt' to the trash or recycle bin instead of deleting it permanently.

If the send2trash() function call raises an exception (i.e., an error), the code will catch the exception with the try/except block and print a message saying that the file couldn't be deleted.

This is a safer way to delete files than using os.unlink() or os.remove(), as it allows users to recover accidentally deleted files from the trash or recycle bin.

Python PIP How To - Install and Uninstall Packages

The "pip" command is a package installer for Python that allows you to easily install and manage third-party libraries or modules. In this case, the "send2trash" library is being installed, which provides a cross-platform way of sending files and folders to the recycle bin or trash instead of permanently deleting them. 

Pip gathers files for installation from the Python Package Index (PyPI), which is a repository of third-party Python packages. PyPI is a central repository of software packages for the Python programming language, where developers and users can publish, search for, and download packages.

When you use pip to install a package, pip searches the PyPI repository for the latest version of the package and downloads the package files from there. The package files can include source code, binary distributions, documentation, and metadata files, such as setup.py and README.md.

Pip also installs any dependencies that the package requires, by recursively searching for and downloading the necessary packages from PyPI.

Microsoft Windows [Version 10.0.18363.900]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\user>pip install send2trash
Collecting send2trash
  Downloading Send2Trash-1.5.0-py3-none-any.whl (12 kB)
Installing collected packages: send2trash
Successfully installed send2trash-1.5.0

C:\Users\user>

This is the output of running the command "pip install send2trash" in a Windows command prompt.

The output shows that the installation was successful, as the "Successfully installed send2trash-1.5.0" message indicates that the library was installed without any errors. 

C:\Users\user>pip uninstall send2trash
Found existing installation: Send2Trash 1.5.0
Uninstalling Send2Trash-1.5.0:
  Would remove:
    c:\python38-64\lib\site-packages\send2trash-1.5.0.dist-info\*
    c:\python38-64\lib\site-packages\send2trash\*
Proceed (y/n)? y
  Successfully uninstalled Send2Trash-1.5.0

C:\Users\user>

The output shows that there was an existing installation of Send2Trash 1.5.0, and it asks for confirmation to proceed with the uninstallation. After confirming by typing 'y', the output confirms that the library has been successfully uninstalled. The output indicates the files and directories that would be removed by the uninstallation process.

For most cases and for the vast majority of Python packages, pip is the most convenient and recommended way to install packages, as it handles dependency management and ensures that packages are installed to the correct location in the system.

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.

Exporting Directory Listing to .TXT File - Python

import os

path = 'c:\\Python38-64\\DLLs'

file = open('simple-report.txt', 'w')

for x in os.listdir(path):
    file.write(x + '\n')

file.close()

This Python code imports the "os" module.

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

The code then uses the "open" function to create a new text file named "simple-report.txt" in write mode (indicated by the 'w' argument) and assigns the file object to the variable "file".

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 "path". For each item in the list, the code writes the name of the item to the file object using the "write" method, followed by a newline character to create a new line in the file.

After the loop, the code closes the file using the "close" method.

So, in essence, the code is trying to create a simple report of all the files in the directory specified by "path". It does this by iterating over all the files and directories in that directory using the "os.listdir" method, and writing the name of each file to a new text file named "simple-report.txt", with each file name on a separate line. 

import os

path = 'c:\\Python38-64\\DLLs'

file = open('simple-report.txt', 'w')

for x in os.listdir(path):
    file.write(path + '\\' + x + '\n')

file.close()

This Python code imports the "os" module.

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

The code then uses the "open" function to create a new text file named "simple-report.txt" in write mode (indicated by the 'w' argument) and assigns the file object to the variable "file".

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 "path". For each item in the list, the code writes the full path of the item to the file object using the "write" method, by concatenating the "path" variable with the file name, separated by a backslash, followed by a newline character to create a new line in the file.

After the loop, the code closes the file using the "close" method.

Listing a Directory in Python - First Level Listing

import os

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

for x in os.listdir(target):
    print(x)

This Python code imports the "os" module.

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

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 prints the name of the item to the console using the "print" method.

Script is trying to list all the files and subdirectories in the directory specified by "target". It does this by iterating over all the files and directories in that directory using the "os.listdir" method, and printing the name of each item to the console.


import os

target = input('Please Enter Dir to Check: ')

for x in os.listdir(target):
    print(x)

The code 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 prints the name of the item to the console using the "print" method.

Find All Files in Directory with Specific Extension

import os

target_path = 'c:\\Python38-64\DLLs'

for x in os.listdir(target_path):
    if x.endswith('.dll'):
        print(x)

This Python code imports the "os" module.

It assigns a string path 'c:\Python38-64\DLLs' to the variable "target_path". This variable represents the path of a directory that contains DLL 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_path". For each item in the list, the code checks if the file name ends with the extension '.dll' by using the "endswith" method.

If the file name ends with '.dll', the code prints the file name to the console using the "print" method.

So, in essence, the code is trying to find all the DLL files in the directory specified by "target_path". It does this by iterating over all the files and directories in that directory using the "os.listdir" method, and checking if each file name ends with the '.dll' extension. If the file name ends with '.dll', the code prints the file name to the console. 

import os

target_path = 'c:\\Python38-64\DLLs'

ext = input('Please enter file type: ')
for x in os.listdir(target_path):
    if x.endswith(ext):
        print(x)

The code prompts the user to enter a file type (e.g., '.txt', '.png', etc.) using the "input" function, and assigns the user input to the variable "ext".

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_path". For each item in the list, the code checks if the file name ends with the extension specified by the user input by using the "endswith" method.

If the file name ends with the specified extension, the code prints the file name to the console using the "print" method.

So, in essence, the code is trying to find all the files of a specified type in the directory specified by "target_path". It does this by prompting the user to enter a file type, and then iterating over all the files and directories in that directory using the "os.listdir" method, and checking if each file name ends with the specified file type.

Remove Multiple Folders with Content

import shutil, time

list_full_dirs = ['FULL-DIR-1', 'c:\\FULL-DIR-IN-ROOT']

for x in list_full_dirs:
    shutil.rmtree(x)
    time.sleep(5)

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

It creates a list of directory names called "list_full_dirs", which contains two directories: 'FULL-DIR-1' and 'c:\FULL-DIR-IN-ROOT'.

The code then uses a "for" loop to iterate over each directory in the list. For each directory, it calls the "rmtree" method of the "shutil" module to remove the directory and its contents. Then, it uses the "time.sleep" method to pause the execution of the script for 5 seconds.

The purpose of using the "time.sleep" method here is to introduce a delay between deleting each directory. This can be useful in cases where there are many directories to be deleted, or where the deletion of a directory is a time-consuming process. By introducing a delay, the script ensures that each directory is fully deleted before moving on to the next one.

So, in essence, the code is trying to remove two directories ('FULL-DIR-1' and 'c:\FULL-DIR-IN-ROOT') from the file system. Each directory is deleted using the "shutil.rmtree" method, and a delay of 5 seconds is introduced between deleting each directory using the "time.sleep" method.

Remove Directory and All of Its Content

import shutil

shutil.rmtree('FULL-DIRECTORY')

This Python code uses the "shutil" module to remove a directory named 'FULL-DIRECTORY' from the file system.

The "shutil" module provides a way of working with high-level file operations such as copying, moving, and deleting files and directories. The "rmtree" method of the "shutil" module is used to delete a directory and all its contents (including any subdirectories and files).

The code is trying to remove the directory named 'FULL-DIRECTORY' from the file system, and all the contents within it will be deleted as well. If the directory does not exist, the "rmtree" method will raise a "FileNotFoundError".

Delete Multiple Empty Folders from List

import os

list_dirs = ['EMPTY-1', 'EMPTY-2', 'C:\\EMPTY-OUTSIDER']

for x in list_dirs:
    os.rmdir(x)

This Python code imports the "os" module which provides a way of using operating system dependent functionality like reading or writing to the file system.

The code then creates a list called "list_dirs" which contains three directory names: 'EMPTY-1', 'EMPTY-2', and 'C:\EMPTY-OUTSIDER'. These directories are represented as strings in the list.

The code then uses a "for" loop to iterate over each directory in the list, and for each directory, it calls the "rmdir" method of the "os" module. This method is used to remove a directory specified by its name.

So, in essence, the code is trying to remove three directories named 'EMPTY-1', 'EMPTY-2', and 'C:\EMPTY-OUTSIDER' from the file system. However, it's important to note that if any of these directories are not empty, the "rmdir" method will raise an error, and the directory will not be deleted.

Delete Empty Directory - Python

import os

os.chdir('c:\\Python38-64\\')

os.rmdir('EMPTY-DIR')

This code uses the os module to remove an empty directory called EMPTY-DIR in the directory c:\\Python38-64\\.

The os.chdir() function is used to change the current working directory to c:\\Python38-64\\, which is where the EMPTY-DIR directory is located.

The os.rmdir() function is then called with the argument 'EMPTY-DIR'. This function is used to remove a directory. However, it only works if the directory is empty. If the directory contains any files or subdirectories, the function will raise an error.

This code is useful for cleaning up empty directories created by a script or for removing unnecessary empty directories. It is important to note that os.rmdir() will only remove empty directories. If you want to remove a directory that contains files or subdirectories, you can use shutil.rmtree() instead. However, use caution when removing directories as the process is irreversible and could result in loss of data if not done carefully.

Delete a File with Python

import os

os.unlink('delete-me.txt')

This code uses the os module to delete a file called delete-me.txt in the current working directory.

The os.unlink() function is used to delete a file. It takes one argument, which is the path to the file that you want to delete. In this case, the argument is 'delete-me.txt', so the file with that name in the current working directory will be deleted.

This code is useful for deleting unnecessary files or for cleaning up after a script has finished running. However, it is important to use caution when deleting files, especially if they contain important data, as the deletion process is irreversible.

Move File to Another Folder - Python

import os, shutil

os.chdir('c:\\')

os.system('mkdir BACKUP')

shutil.move('c:\\Python38-64\\copy-me.txt', 'c:\\BACKUP')

This code uses the os and shutil modules to move a file called copy-me.txt from the c:\\Python38-64\\ directory to a new directory called BACKUP in the root directory of the C: drive (c:\\).

The first line of code imports the os and shutil modules.

The os.chdir() function is used to change the current working directory to the root directory of the C: drive (c:\\). This is done to ensure that the new directory is created in the correct location.

The os.system() function is then called with the argument 'mkdir BACKUP'. This command is executed in the command prompt to create a new directory called BACKUP in the current working directory, which is the root directory of the C: drive in this case. The os.system() function allows us to execute a shell command from within our Python script.

The shutil.move() function is then called with two arguments: the source file (c:\\Python38-64\\copy-me.txt) and the destination directory (c:\\BACKUP). The shutil module provides a way to move files and directories in a platform-independent manner.

This code is useful for automating the backup of important files and ensuring that they are stored in a safe location. 

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