File size: 1,796 Bytes
00b2f69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
{
 "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
}