Cleaning Up Text Files in Directory

I have a problem. I wrote a Python script that left a lot of .txt files in a Node.js project directory. There are roughly 410 txt files and now I need to delete them. This is something I will automate with Python.

First, I will open a new file in the project directory.

$ nano cleanup.py

Next, I will write my Python script.

#! /opt/homebrew/bin/python3
import os


# Recursive function to walk through all subdirectories
def delete_txt_files(dir):
    for item in os.listdir(dir):
        item_path = os.path.join(dir, item)
        if os.path.isfile(item_path) and item_path.endswith('.txt'):
            os.remove(item_path)
        elif os.path.isdir(item_path):
            delete_txt_files(item_path)


# Start the process in the current directory
delete_txt_files(os.getcwd())
print("All .txt files have been deleted.")

This function does the following:

  1. Get a list of items in a directory by using os.listdir()
  2. Loop through each item in the list
  3. Check to see if the file ends with .txt. If it does, remove the file using os.remove().
  4. Check to see if the item is a directory. If so, the function calls itself.

This function calling itself makes it known as a recursive function. Each time this function calls itself, a new instance of that function is created, known as a function call frame. Each call to the function is responsible for processing one directory. It will create new calls to itself to scan subdirectories. This will continue until all files and subdirectories in a directory have been processed. When all the files and directories in a directory have been processed, the function returns, and its call frame is discarded.

Now that I have written the file, I need to run it. First, I need to make the file executable. I can do this by running the chmod command.

$ chmod +x cleanup.py

Finally, I run my script using the python3 command and the path to my script. To confirm that it worked, I can run the ls command and make sure that the script did delete all of the files.

$ python3 cleanup.py
All .txt files have been deleted.

And there you have it! With Python, you can quickly take care of tasks that would take a long time to do manually. If this is too much work, open a terminal window and enter the following command in your project directory.

rm -R *.txt

Leave a Reply

Your email address will not be published. Required fields are marked *