0% found this document useful (0 votes)
6 views

Image_Renamer_In_Python

Uploaded by

lemonsplashvegan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Image_Renamer_In_Python

Uploaded by

lemonsplashvegan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

import os

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# Define the list of folders to monitor


FOLDERS_TO_MONITOR = [
"replace", # Replace with the path to the first folder
"replace", # Replace with the path to the second folder
# Add more folder paths as needed
]
VALID_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".tiff",
".bmp"}

class ImageHandler(FileSystemEventHandler):
def on_created(self, event):
# Triggered when a new file is added to the folder
if not event.is_directory:
file_path = event.src_path
_, ext = os.path.splitext(file_path)
if ext.lower() in VALID_EXTENSIONS:
self.rename_image(file_path)

def rename_image(self, file_path):


folder = os.path.dirname(file_path)
existing_files = [
f for f in os.listdir(folder)
if os.path.isfile(os.path.join(folder, f)) and
os.path.splitext(f)[1].lower() in VALID_EXTENSIONS
]

# Extract numbers from existing files and find the next


available number
max_number = 0
for file in existing_files:
if "_" in file:
try:
number_part = file.split("_")[0]
number = int(number_part)
max_number = max(max_number, number)
except ValueError:
pass

# Determine the new number and rename the file


new_number = max_number + 1
new_name = f"{new_number:02d}_" +
os.path.basename(file_path)
new_path = os.path.join(folder, new_name)
os.rename(file_path, new_path)
print(f"Renamed {file_path} to {new_path}")

if __name__ == "__main__":
# Ensure all specified folders exist
for folder in FOLDERS_TO_MONITOR:
if not os.path.exists(folder):
print(f"Folder '{folder}' does not exist. Please
check the path.")
exit(1)

print(f"Monitoring folders: {',


'.join(FOLDERS_TO_MONITOR)}")
event_handler = ImageHandler()
observer = Observer()

# Schedule the handler for each folder


for folder in FOLDERS_TO_MONITOR:
observer.schedule(event_handler, folder,
recursive=False)

observer.start()

try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()

You might also like