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

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'):
        elif os.path.isdir(item_path):

# Start the process in the current directory
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

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