自动化查找并记录含图片文件夹的Python脚本

发布时间 2023-12-18 20:15:49作者: 不上火星不改名

功能介绍

此Python脚本用于遍历指定的父目录,自动识别并记录所有包含图片文件(如PNG、JPG、GIF等格式)的子文件夹。脚本运行后,将在父目录下生成一个名为“文件夹名统计”的Excel表格,其中列出了所有含有图片的文件夹名称。这对于整理大量分散在不同子文件夹中的图片文件特别有用,尤其是在图像管理和分类方面。

 

import os
import pandas as pd

def find_image_folders(parent_directory):
    """
    遍历父目录,寻找所有包含图片的子目录。
    返回一个包含有图片的文件夹名称的列表。
    """
    image_folders = []
    for root, dirs, files in os.walk(parent_directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.webp')):
                folder_name = os.path.basename(root)
                if folder_name not in image_folders:
                    image_folders.append(folder_name)
                break  # 一旦找到图片,停止搜索该目录
    return image_folders

def create_excel_file(parent_directory, folder_names):
    """
    在父目录中创建一个Excel文件,列出文件夹名称。
    """
    df = pd.DataFrame(folder_names, columns=["文件夹名称"])
    output_path = os.path.join(parent_directory, "文件夹名统计.xlsx")
    df.to_excel(output_path, index=False)
    return output_path

# 使用方法
parent_directory = input("请输入父目录的路径: ")
image_folders = find_image_folders(parent_directory)
excel_file_path = create_excel_file(parent_directory, image_folders)
print(f"Excel文件已创建在: {excel_file_path}")