***批次修改資料夾名稱

不上火星不改名發表於2024-06-11

1.統計資料夾結構下資訊

import os
import openpyxl
from openpyxl import Workbook

# 詢問使用者輸入資料夾路徑
folder_path = input("請輸入資料夾路徑: ")

# 定義圖片副檔名
image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp']

def is_image_file(filename):
    return any(filename.lower().endswith(ext) for ext in image_extensions)

def cleanup_folder(folder):
    for root, dirs, files in os.walk(folder):
        for file in files:
            if not is_image_file(file) and not os.path.isdir(os.path.join(root, file)):
                os.remove(os.path.join(root, file))

def find_image_folders(folder):
    image_folders = []
    for root, dirs, files in os.walk(folder):
        if any(is_image_file(file) for file in files):
            image_folders.append(root)
    return image_folders

def create_excel(folder, image_folders):
    # 獲取資料夾名稱作為表格名稱
    folder_name = os.path.basename(os.path.normpath(folder))
    excel_path = os.path.join(folder, f"{folder_name}.xlsx")

    # 建立Excel工作簿
    wb = Workbook()
    ws = wb.active
    ws.title = "Image Folders"

    # 將資料夾名稱寫入第一列和第二列
    for idx, image_folder in enumerate(image_folders, start=1):
        folder_name_only = os.path.basename(image_folder)
        ws.cell(row=idx, column=1, value=image_folder)
        ws.cell(row=idx, column=2, value=folder_name_only)

    # 儲存Excel檔案
    wb.save(excel_path)

def main():
    # 清理資料夾,刪除非圖片和非資料夾類檔案
    cleanup_folder(folder_path)
    
    # 查詢所有包含圖片的資料夾
    image_folders = find_image_folders(folder_path)
    
    # 建立Excel表格並寫入資料
    create_excel(folder_path, image_folders)

if __name__ == "__main__":
    main()

2.excel表格內部處理,只留中文(ctrl+shirft+enter)(b2)

=TEXTJOIN("", TRUE, IF(UNICODE(MID(B2, ROW(INDIRECT("1:" & LEN(B2))), 1)) >= 19968, MID(B2, ROW(INDIRECT("1:" & LEN(B2))), 1), ""))

3.複製資料到新表格(只有值),並操作以下程式碼。

import os
import shutil
import pandas as pd

def get_user_input():
    excel_path = input("請輸入Excel表格路徑: ")
    folder_path = input("請輸入資料夾地址: ")
    input_col_index = int(input("請輸入輸入列號(從1開始): ")) - 1
    rename_col_index = int(input("請輸入重新命名列號(從1開始): ")) - 1
    return excel_path, folder_path, input_col_index, rename_col_index

def read_excel(excel_path, input_col_index, rename_col_index):
    try:
        df = pd.read_excel(excel_path)
        
        if df.empty:
            print("Excel檔案為空,請檢查檔案內容。")
            return None, None
        
        print("讀取到的Excel表格內容:")
        print(df.head())
        
        num_columns = len(df.columns)
        if input_col_index >= num_columns or rename_col_index >= num_columns:
            raise IndexError(f"列號超出範圍,請檢查輸入的列號是否正確。表格有 {num_columns} 列。")
        
        input_col = df.iloc[:, input_col_index].astype(str).str.strip()
        rename_col = df.iloc[:, rename_col_index].astype(str).str.strip()
        
        return input_col, rename_col
    except FileNotFoundError:
        print(f"檔案未找到: {excel_path}")
        return None, None
    except ValueError as e:
        print(f"讀取Excel檔案時發生值錯誤: {e}")
        return None, None
    except Exception as e:
        print(f"讀取Excel表格時發生錯誤: {e}")
        return None, None

def delete_folder(path):
    try:
        shutil.rmtree(path)
        print(f"成功刪除資料夾: {path}")
    except Exception as e:
        print(f"刪除資料夾 {path} 時發生錯誤: {e}")

def process_folders(folder_path, input_col, rename_col):
    if not os.path.exists(folder_path):
        print(f"資料夾路徑不存在: {folder_path}")
        return
    
    for root, dirs, _ in os.walk(folder_path, topdown=False):
        if not dirs:
            folder_name = os.path.basename(root)
            if folder_name in input_col.values:
                new_name = rename_col[input_col[input_col == folder_name].index[0]]
                new_folder_path = os.path.join(os.path.dirname(root), new_name)
                if new_name not in os.listdir(os.path.dirname(root)):
                    try:
                        os.rename(root, new_folder_path)
                        print(f"重新命名資料夾 {root} 為 {new_folder_path}")
                    except Exception as e:
                        print(f"重新命名資料夾 {root} 時發生錯誤: {e}")
                else:
                    print(f"資料夾 {new_folder_path} 已存在。刪除新的資料夾 {root}.")
                    delete_folder(root)
            else:
                print(f"資料夾 {folder_name} 在輸入列中未找到。刪除資料夾 {root}.")
                delete_folder(root)

def main():
    excel_path, folder_path, input_col_index, rename_col_index = get_user_input()
    input_col, rename_col = read_excel(excel_path, input_col_index, rename_col_index)
    if input_col is not None and rename_col is not None:
        process_folders(folder_path, input_col, rename_col)
    else:
        print("處理停止。請檢查輸入並重試。")

if __name__ == "__main__":
    main()

相關文章