{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Rename images and captions to MD5\n", "\n", "This Python script recursively traverses a specified directory, identifies image files with extensions .jpg, .jpeg, or .png, calculates their MD5 hash values, and renames them accordingly. Additionally, it renames accompanying text files (.txt, .caption, .tags) to match the new filename while preserving their original content associations." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files renamed successfully!\n" ] } ], "source": [ "import os\n", "import hashlib\n", "\n", "def md5(file_path):\n", " \"\"\"Calculate MD5 hash of a file.\"\"\"\n", " hash_md5 = hashlib.md5()\n", " with open(file_path, \"rb\") as f:\n", " for chunk in iter(lambda: f.read(4096), b\"\"):\n", " hash_md5.update(chunk)\n", " return hash_md5.hexdigest()\n", "\n", "def rename_files(directory):\n", " \"\"\"Recursively rename image and accompanying text files.\"\"\"\n", " for root, _, files in os.walk(directory):\n", " for file in files:\n", " file_path = os.path.join(root, file)\n", " file_name, file_ext = os.path.splitext(file)\n", " if file_ext.lower() in ('.jpg', '.jpeg', '.png'):\n", " # Calculate MD5 hash\n", " new_file_name = md5(file_path) + file_ext.lower()\n", " # Check if the new filename already exists\n", " if os.path.exists(os.path.join(root, new_file_name)):\n", " # Add a suffix to make the filename unique\n", " suffix = 1\n", " while True:\n", " new_file_name = md5(file_path) + '_' + str(suffix) + file_ext.lower()\n", " if not os.path.exists(os.path.join(root, new_file_name)):\n", " break\n", " suffix += 1\n", " # Rename image file\n", " os.rename(file_path, os.path.join(root, new_file_name))\n", " # Rename accompanying text files\n", " for ext in ('.txt', '.caption', '.tags'):\n", " txt_file = os.path.join(root, file_name + ext)\n", " if os.path.exists(txt_file):\n", " new_txt_file = os.path.join(root, new_file_name.replace(file_ext.lower(), '') + ext)\n", " os.rename(txt_file, new_txt_file)\n", "\n", "# Specify the directory\n", "directory = r'C:\\Users\\kade\\Desktop\\1_by_spaceengine'\n", "\n", "# Call the function to rename files\n", "rename_files(directory)\n", "\n", "print(\"Files renamed successfully!\")" ] } ], "metadata": { "kernelspec": { "display_name": "base", "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.12.3" } }, "nbformat": 4, "nbformat_minor": 2 }