Phần 1: Quét thư mục và tạo file Excel
Script Python dưới đây sẽ quét một thư mục, xác định các thư mục chứa file ảnh, và tạo một file Excel liệt kê đường dẫn đầy đủ và tên của các thư mục đó. Điều này giúp bạn chuẩn bị dữ liệu cần thiết cho bước đổi tên.
import os
import openpyxl
from openpyxl import Workbook
# Yêu cầu người dùng nhập đường dẫn thư mục
duong_dan_thu_muc = input("Vui lòng nhập đường dẫn thư mục: ")
# Định nghĩa các phần mở rộng file ảnh
duoi_anh = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp']
def la_tep_anh(ten_tep):
"""Kiểm tra xem một file có phải là file ảnh không."""
return any(ten_tep.lower().endswith(ext) for ext in duoi_anh)
def sach_sach_thu_muc(duong_dan):
"""Xóa các file không phải ảnh và không phải thư mục trong một thư mục."""
for root, dirs, files in os.walk(duong_dan):
for file in files:
if not la_tep_anh(file) and not os.path.isdir(os.path.join(root, file)):
os.remove(os.path.join(root, file))
def tim_thu_muc_anh(duong_dan):
"""Tìm tất cả các thư mục chứa ít nhất một file ảnh."""
thu_muc_anh = []
for root, dirs, files in os.walk(duong_dan):
if any(la_tep_anh(file) for file in files):
thu_muc_anh.append(root)
return thu_muc_anh
def tao_file_excel(duong_dan, danh_sach_thu_muc):
"""Tạo một file Excel từ danh sách các thư mục ảnh."""
# Lấy tên thư mục gốc làm tên cho file Excel
ten_thu_muc_goc = os.path.basename(os.path.normpath(duong_dan))
duong_dan_excel = os.path.join(duong_dan, f"{ten_thu_muc_goc}.xlsx")
# Tạo workbook và worksheet mới
wb = Workbook()
ws = wb.active
ws.title = "Danh sách thư mục ảnh"
# Ghi tên thư mục vào cột đầu tiên và thứ hai
for i, thu_muc in enumerate(danh_sach_thu_muc, start=1):
ten_thu_muc = os.path.basename(thu_muc)
ws.cell(row=i, column=1, value=thu_muc)
ws.cell(row=i, column=2, value=ten_thu_muc)
# Lưu file Excel
wb.save(duong_dan_excel)
print(f"Đã tạo file Excel tại: {duong_dan_excel}")
def chay_chuong_trinh():
"""Hàm chính để thực thi các bước."""
# Dọn dẹp thư mục, xóa các file không phải ảnh
sach_sach_thu_muc(duong_dan_thu_muc)
# Tìm tất cả các thư mục chứa ảnh
danh_sach_thu_muc_anh = tim_thu_muc_anh(duong_dan_thu_muc)
# Tạo file Excel và ghi dữ liệu
tao_file_excel(duong_dan_thu_muc, danh_sach_thu_muc_anh)
if __name__ == "__main__":
chay_chuong_trinh()
Phần 2: Sử dụng công thức Excel để lọc ký tự Trung Quốc
Trong file Excel vừa tạo, nếu tên thư mục gốc chứa ký tự không phải Trung Quốc, bạn có thể sử dụng công thức sau trong ô C2 (và kéo xuống) để chỉ giữ lại các ký tự Trung Quốc. Nhấn Ctrl+Shift+Enter để áp dụng công thức mảng.
=TEXTJOIN("", TRUE, IF(UNICODE(MID(B2, ROW(INDIRECT("1:" & LEN(B2))), 1)) >= 19968, MID(B2, ROW(INDIRECT("1:" & LEN(B2))), 1), ""))
Phần 3: Chạy script Python để đổi tên thư mục
Script này sẽ đọc file Excel bạn đã chuẩn bị, sau đó đổi tên các thư mục con dựa trên dữ liệu trong file. Hãy đảm bảo bạn đã sao chép dữ liệu từ file Excel (chỉ giá trị) vào một file mới trước khi chạy script này.
import os
import shutil
import pandas as pd
def nhap_thong_tin_nguoi_dung():
"""Nhận đầu vào từ người dùng."""
duong_dan_excel = input("Vui lòng nhập đường dẫn file Excel: ")
duong_dan_thu_muc_chinh = input("Vui lòng nhập đường dẫn thư mục chính: ")
chi_so_cot_dau_vao = int(input("Vui lòng nhập số cột nguồn (bắt đầu từ 1): ")) - 1
chi_so_cot_ten_moi = int(input("Vui lòng nhập số cột tên mới (bắt đầu từ 1): ")) - 1
return duong_dan_excel, duong_dan_thu_muc_chinh, chi_so_cot_dau_vao, chi_so_cot_ten_moi
def doc_file_excel(duong_dan_excel, chi_so_cot_dau_vao, chi_so_cot_ten_moi):
"""Đọc dữ liệu từ file Excel."""
try:
df = pd.read_excel(duong_dan_excel)
if df.empty:
print("File Excel trống. Vui lòng kiểm tra nội dung.")
return None, None
print("Nội dung file Excel đã đọc:")
print(df.head())
so_cot = len(df.columns)
if chi_so_cot_dau_vao >= so_cot or chi_so_cot_ten_moi >= so_cot:
raise IndexError(f"Số cột không hợp lệ. Bảng có {so_cot} cột.")
cot_dau_vao = df.iloc[:, chi_so_cot_dau_vao].astype(str).str.strip()
cot_ten_moi = df.iloc[:, chi_so_cot_ten_moi].astype(str).str.strip()
return cot_dau_vao, cot_ten_moi
except FileNotFoundError:
print(f"Không tìm thấy file: {duong_dan_excel}")
return None, None
except ValueError as e:
print(f"Lỗi giá trị khi đọc file Excel: {e}")
return None, None
except Exception as e:
print(f"Lỗi khi đọc file Excel: {e}")
return None, None
def xoa_thu_muc(duong_dan):
"""Xóa một thư mục và toàn bộ nội dung bên trong."""
try:
shutil.rmtree(duong_dan)
print(f"Đã xóa thành công thư mục: {duong_dan}")
except Exception as e:
print(f"Lỗi khi xóa thư mục {duong_dan}: {e}")
def xu_ly_thu_muc(duong_dan_thu_muc_chinh, cot_dau_vao, cot_ten_moi):
"""Thực hiện đổi tên hoặc xóa các thư mục con."""
if not os.path.exists(duong_dan_thu_muc_chinh):
print(f"Đường dẫn thư mục không tồn tại: {duong_dan_thu_muc_chinh}")
return
# Duyệt thư mục từ dưới lên để tránh xung đột khi đổi tên
for root, dirs, _ in os.walk(duong_dan_thu_muc_chinh, topdown=False):
if not dirs: # Chỉ xử lý các thư mục rỗng (không có thư mục con)
ten_thu_muc = os.path.basename(root)
if ten_thu_muc in cot_dau_vao.values:
# Lấy tên mới tương ứng
chi_so = cot_dau_vao[cot_dau_vao == ten_thu_muc].index[0]
ten_moi = cot_ten_moi[chi_so]
duong_dan_thu_muc_moi = os.path.join(os.path.dirname(root), ten_moi)
# Kiểm tra xem thư mục mới đã tồn tại chưa
if ten_moi not in os.listdir(os.path.dirname(root)):
try:
os.rename(root, duong_dan_thu_muc_moi)
print(f"Đã đổi tên thư mục {root} thành {duong_dan_thu_muc_moi}")
except Exception as e:
print(f"Lỗi khi đổi tên thư mục {root}: {e}")
else:
print(f"Thư mục {duong_dan_thu_muc_moi} đã tồn tại. Sẽ xóa thư mục cũ {root}.")
xoa_thu_muc(root)
else:
print(f"Không tìm thấy thư mục {ten_thu_muc} trong dữ liệu nguồn. Sẽ xóa thư mục {root}.")
xoa_thu_muc(root)
def chay_chuong_trinh_chinh():
"""Hàm chính để điều phối các bước."""
duong_dan_excel, duong_dan_thu_muc_chinh, chi_so_cot_dau_vao, chi_so_cot_ten_moi = nhap_thong_tin_nguoi_dung()
cot_dau_vao, cot_ten_moi = doc_file_excel(duong_dan_excel, chi_so_cot_dau_vao, chi_so_cot_ten_moi)
if cot_dau_vao is not None and cot_ten_moi is not None:
xu_ly_thu_muc(duong_dan_thu_muc_chinh, cot_dau_vao, cot_ten_moi)
else:
print("Quá trình dừng lại. Vui lòng kiểm tra đầu vào và thử lại.")
if __name__ == "__main__":
chay_chuong_trinh_chinh()