我使用下面的代码来访问文件夹中最后修改过的图像文件。
由于3-4图像将在一分钟内上传,我想获得访问所有的3-4文件和重命名。我希望在将新图像添加到文件夹后立即运行相同的进程。
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)发布于 2021-09-05 13:21:09
您好,不知道我是否理解正确,但如果您想在img文件进入目录后立即更改它的名称,有一种方法可以使用watchdog libery来完成此操作
在这里查看docomantaion https://pypi.org/project/watchdog/
pip install watchdog然后像这样使用它
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()有关如何使用该库的更多示例,请参阅https://www.geeksforgeeks.org/create-a-watchdog-in-python-to-look-for-filesystem-changes/
发布于 2021-09-12 05:13:24
使用Watchdog确实可以帮助我在将图像添加到文件夹时立即触发重命名脚本。图像的新名称是从一个不断更新的excel表格中收集的。
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()https://stackoverflow.com/questions/69061857
复制相似问题