{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Remove extra file extension before `.txt`\n", "----\n", "\n", "Recursively renames `.txt` files with additional image extensions before in the filename in the specified directory and its subdirectories." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "def rename_files(directory_path):\n", " for root, dirs, files in os.walk(directory_path):\n", " for filename in files:\n", " if filename.endswith('.txt'):\n", " # Extract the base name without extension\n", " base_name, extension = os.path.splitext(filename)\n", "\n", " # Check if the file has an additional image extension\n", " if base_name.endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif')):\n", " # Construct the new filename with only the txt extension\n", " new_filename = base_name[:-4] + '.txt'\n", "\n", " # Construct the full file paths\n", " old_path = os.path.join(root, filename)\n", " new_path = os.path.join(root, new_filename)\n", "\n", " # Rename the file\n", " os.rename(old_path, new_path)\n", "\n", "# Specify the directory path\n", "directory_path = r'C:\\Users\\kade\\Desktop\\training_dir_staging'\n", "\n", "# Call the function to recursively rename files\n", "rename_files(directory_path)" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }