[Python] 纯文本查看 复制代码import os
import shutil
from tkinter import filedialog, messagebox
import tkinter as tk
def rename_and_move_images(folder_path, new_folder_path):
# 创建新的文件夹
os.makedirs(new_folder_path, exist_ok=True)
# 遍历文件夹中的文件
for file_name in os.listdir(folder_path):
# 获取文件的完整路径
file_path = os.path.join(folder_path, file_name)
# 检查文件是否为图片
if not file_path.endswith(('.jpg', '.jpeg', '.png')):
continue
# 构建新文件的完整路径,这里使用了新文件夹路径和原始文件名
new_file_path = os.path.join(new_folder_path, file_name)
# 检查新文件是否已存在
if os.path.exists(new_file_path):
# 如果存在,添加一个数字后缀,直到找到一个可用的文件名
suffix = 1
while True:
name, extension = os.path.splitext(file_name)
new_file_name = f"{name}_{suffix}{extension}"
new_file_path = os.path.join(new_folder_path, new_file_name)
if not os.path.exists(new_file_path):
break
suffix += 1
# 复制文件并重命名
shutil.copy2(file_path, new_file_path)
print(f"Copied and renamed image: {file_name} -> {new_file_name}")
def select_folder():
folder_path = filedialog.askdirectory()
entry_folder_path.delete(0, tk.END)
entry_folder_path.insert(0, folder_path)
def select_new_folder():
new_folder_path = filedialog.askdirectory()
entry_new_folder_path.delete(0, tk.END)
entry_new_folder_path.insert(0, new_folder_path)
def process_images():
folder_path = entry_folder_path.get()
new_folder_path = entry_new_folder_path.get()
if not folder_path or not new_folder_path:
messagebox.showerror("Error", "Please select folder paths.")
return
try:
rename_and_move_images(folder_path, new_folder_path)
messagebox.showinfo("Success", "Images processed and moved successfully.")
except Exception as e:
messagebox.showerror("Error", str(e))
# 创建主窗口
window = tk.Tk()
window.title("Image Processing")
window.geometry("400x200")
# 创建文件夹路径选择部件
label_folder_path = tk.Label(window, text="源文件夹")
label_folder_path.pack()
entry_folder_path = tk.Entry(window, width=50)
entry_folder_path.pack()
button_select_folder = tk.Button(window, text="选择", command=select_folder)
button_select_folder.pack()
# 创建新文件夹路径选择部件
label_new_folder_path = tk.Label(window, text="新文件夹")
label_new_folder_path.pack()
entry_new_folder_path = tk.Entry(window, width=50)
entry_new_folder_path.pack()
button_select_new_folder = tk.Button(window, text="选择", command=select_new_folder)
button_select_new_folder.pack()
# 创建处理按钮
button_process = tk.Button(window, text="开始", command=process_images)
button_process.pack()
# 运行主循环
window.mainloop()