File size: 1,917 Bytes
00b2f69 bbfc683 00b2f69 bbfc683 00b2f69 bbfc683 00b2f69 bbfc683 00b2f69 bbfc683 00b2f69 bbfc683 00b2f69 bbfc683 00b2f69 bbfc683 00b2f69 bbfc683 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 57 58 59 60 61 62 63 64 65 66 67 68 |
{
"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
}
|