Need to get most recently uploaded image names within a folder. I wish to rename and replace it in the same folder

Viewed 74

I am using the below code to get access to the last modified image file in a folder.

Since 3-4 images will be uploaded within a span of minute, I want to get access all the 3-4 files and rename it. I want the same process to run as soon as the new images are added to the folder.

import pandas as pd
import glob
import os
import os.path

#Find the last updated Image

folder_path = r'C:\Users\folder\path\for\images' 
file_type = '\*jpg' 
files = glob.glob(folder_path + file_type)
max_file = max(files, key = os.path.getctime)
print(max_file)

#Load the last updated engine number

df = pd.read_excel("g-ng.xlsx")
engine_no = df['engine_no'].iloc[-1]
print(engine_no)

#create new name for the file
new_fol_path = r'C:\Users\folder\path\for\images' "\\"
new_name = new_fol_path + engine_no + ".jpg"
print(new_name)

renamed = os.rename(max_file,new_name)
print(renamed)
2 Answers

Hi not sure if I understand you correctly but if you want to change an img file name as soon as it enters the directory there is a way to do this using watchdog libery

see docomantaion here https://pypi.org/project/watchdog/

pip install watchdog

and then use it like this

import watchdog.events
import watchdog.observers
import time
  
  
class Handler(watchdog.events.PatternMatchingEventHandler):
    def __init__(self):
        # Set the patterns for PatternMatchingEventHandler
        watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.jpg'],
                                                             ignore_directories=True, case_sensitive=False)
  
    def on_created(self, event):
        ### enter your code here and change and save name 
        print("Watchdog received created event - % s." % event.src_path)
        # Event is created, you can process it now
  
    def on_modified(self, event):
        print("Watchdog received modified event - % s." % event.src_path)
        # Event is modified, you can process it now
  
  
if __name__ == "__main__":
    src_path = r'C:\Users\folder\path\for\images'
    event_handler = Handler()
    observer = watchdog.observers.Observer()
    observer.schedule(event_handler, path=src_path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

see https://www.geeksforgeeks.org/create-a-watchdog-in-python-to-look-for-filesystem-changes/ for more example on how to use this library

Using Watchdog did help me trigger my renaming script as soon as an image gets added to the folder. The new names for the image is collected from an excel sheet which keeping getting updated continuously.

date = time.strftime("%Y%m%d")
print(date)

path = r"your path to folder"

#os.chdir()
class OnMyWatch:
    # Set the directory on watch
    watchDirectory = path
  
    def __init__(self):
        self.observer = Observer()
  
    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.watchDirectory, recursive = True)
        self.observer.start()
        try:
            while True:
                time.sleep(30)
        except:
            self.observer.stop()
            print("Observer Stopped")
  
        self.observer.join()
  
  
class Handler(FileSystemEventHandler):
  
    
    def on_any_event(self, event):
        if event.is_directory:
            return None
  
        elif event.event_type == 'created':
            # Event is created, you can process it now 
            
            img_folder = os.listdir(path)
            print(path, img_folder)
            img_name = []
            for img in img_folder:
                name, ext = img.split(".")
                img_name.append(name)

            print(img_name)


            time_chunk=[]
            for x in img_name:
                y = x[:11]
                time_chunk.append(y)

            print(time_chunk)


            df = pd.read_excel(r"path to excel file")
            engine_no = df['engine_no'].iloc[-1]
            date_time = str(df['date_time'].iloc[-1])

            print(engine_no)
            print(date_time[:11])


            #old_folder = []
            no = 0
            for i in time_chunk:

                old_path = path +"\\" + img_name[no] + '.jpg'
                print(img_name[no])
                #old_folder.append(old_path)
                new_path = path + "\\" + engine_no + '_' +str(no) + '.jpg'
                print(i)
                no += 1
                if i == date_time[:11]:
                    rename = os.rename(old_path, new_path)
           
#         elif event.event_type == 'modified':
#              return None
                      
if __name__ == '__main__':
    watch = OnMyWatch()
    watch.run()
Related