Use Case
/
个人任务自动化
创建自定义脚本和工具以简化日常任务并提高效率
Model
•
Claude 3.7 十四行诗
编写一个跨平台的 Python 脚本,每小时扫描一次我的下载文件夹,并自动重命名图像文件并将其移动到带有日期戳的子文件夹。
自动图像文件管理器
这是一个跨平台的 Python 脚本,它每小时扫描一次你的下载文件夹,识别图像文件,并根据它们的创建/修改日期将它们组织成带有日期戳的子文件夹:
1import os
2import shutil
3import time
4import datetime
5import schedule
6import platform
7import logging
8from pathlib import Path
9from PIL import Image
10from PIL.ExifTags import TAGS
11
12# Set up logging
13logging.basicConfig(
14 level=logging.INFO,
15 format='%(asctime)s - %(levelname)s - %(message)s',
16 handlers=[
17 logging.FileHandler("image_organizer.log"),
18 logging.StreamHandler()
19 ]
20)
21
22def get_downloads_folder():
23 """Get the downloads folder path based on the operating system"""
24 if platform.system() == "Windows":
25 return os.path.join(os.path.expanduser("~"), "Downloads")
26 elif platform.system() == "Darwin": # macOS
27 return os.path.join(os.path.expanduser("~"), "Downloads")
28 else: # Linux and other Unix-like
29 return os.path.join(os.path.expanduser("~"), "Downloads")
30
31def get_image_date(file_path):
32 """Extract date from image metadata or use file modification date"""
33 try:
34 # Try to get date from EXIF data
35 with Image.open(file_path) as img:
36 exif_data = img._getexif()
37 if exif_data:
38 for tag_id, value in exif_data.items():
39 tag = TAGS.get(tag_id, tag_id)
40 if tag == "DateTimeOriginal":
41 # Parse the date string (format: YYYY:MM:DD HH:MM:SS)
42 date_str = value.split()[0].replace(":", "-")
43 return date_str
44 except (AttributeError, KeyError, IndexError, TypeError, OSError):
45 pass
46
47 # Fall back to file modification time
48 mod_time = os.path.getmtime(file_path)
49 date_str = datetime.datetime.fromtimestamp(mod_time).strftime('%Y-%m-%d')
50 return date_str
51
52def is_image_file(file_path):
53 """Check if the file is an image based on extension"""
54 image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp', '.heic'}
55 return os.path.splitext(file_path.lower())[1] in image_extensions
56
57def organize_images():
58 """Scan downloads folder and organize images into date-based folders"""
59 downloads_folder = get_downloads_folder()
60 logging.info(f"Scanning {downloads_folder} for images...")
61
62 # Create a base folder for organized images
63 organized_folder = os.path.join(downloads_folder, "Organized_Images")
64 if not os.path.exists(organized_folder):
65 os.makedirs(organized_folder)
66
67 # Get all files in downloads folder
68 files = [f for f in os.listdir(downloads_folder) if os.path.isfile(os.path.join(downloads_folder, f))]
69
70 # Counter for renamed files
71 moved_count = 0
72
73 for file_name in files:
74 file_path = os.path.join(downloads_folder, file_name)
75
76 # Skip the script itself and non-image files
77 if not is_image_file(file_path):
78 continue
79
80 try:
81 # Get date from image
82 date_str = get_image_date(file_path)
83
84 # Create date folder if it doesn't exist
85 date_folder = os.path.join(organized_folder, date_str)
86 if not os.path.exists(date_folder):
87 os.makedirs(date_folder)
88
89 # Generate a unique name for the file
90 file_ext = os.path.splitext(file_name)[1]
91 new_file_name = f"{date_str}_{int(time.time())}_{moved_count}{file_ext}"
92 new_file_path = os.path.join(date_folder, new_file_name)
93
94 # Move and rename the file
95 shutil.move(file_path, new_file_path)
96 logging.info(f"Moved: {file_name} -> {new_file_path}")
97 moved_count += 1
98
99 except Exception as e:
100 logging.error(f"Error processing {file_name}: {str(e)}")
101
102 logging.info(f"Organized {moved_count} images")
103
104def main():
105 """Main function to schedule and run the image organization task"""
106 logging.info("Image Organizer started")
107
108 # Run once at startup
109 organize_images()
110
111 # Schedule to run every hour
112 schedule.every(1).hour.do(organize_images)
113
114 # Keep the script running
115 while True:
116 schedule.run_pending()
117 time.sleep(60) # Check every minute
118
119if __name__ == "__main__":
120 main()
如何使用这个脚本
- 安装所需的软件包:
1pip install pillow schedule- 运行脚本:
- 它将根据您的操作系统自动检测您的下载文件夹
- 图像将整理到您的下载文件夹中一个名为 “Organized_Images” 的文件夹中
- 每张图像将放置在以其创建日期 (YYYY-MM-DD) 命名的子文件夹中
- 图像将使用以下模式重命名:date_timestamp_counter.extension
- 特征:
- 跨平台(适用于 Windows、macOS 和 Linux)
- 在可用时使用 EXIF 数据来确定图像日期
- 当 EXIF 数据不可用时,回退到文件修改日期
- 将所有操作记录到控制台和日志文件中
- 启动时运行一次,之后每小时运行一次
- 优雅地处理错误
- 在后台运行脚本:
- 在 Windows 上:创建计划任务
- 在 macOS/Linux 上:使用 cron 任务或创建服务
该脚本将继续运行,直到你停止它,每小时检查一次你的下载文件夹,并整理所有新的图像文件。
Explore Related Use Cases
Experience Ninja's AI Assistant
Try for free today. Plans starting at $19/month.


