{ "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": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "import glob\n", "\n", "def rename_files(directory_path):\n", " for file_path in glob.glob(os.path.join(directory_path, '**', '*.txt')):\n", " # Extract the base name without extension\n", " base_name, _ = os.path.splitext(os.path.basename(file_path))\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", " new_path = os.path.join(os.path.dirname(file_path), new_filename)\n", "\n", " # Rename the file\n", " os.rename(file_path, new_path)\n", "\n", "# Specify the directory path\n", "directory_path = r'E:\\training_dir'\n", "\n", "# Call the function to recursively rename files\n", "rename_files(directory_path)" ] } ], "metadata": { "kernelspec": { "display_name": "ml", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.8" } }, "nbformat": 4, "nbformat_minor": 2 }