Chào mọi người,
Dạo gần đây mình có làm một dự án nhỏ liên quan đến việc quản lý ảnh. Thường thì mình phải mở từng thư mục, xem ảnh rồi ghi chú lại tên file, kích thước, ngày tạo,... Khá là mất thời gian. Nên mình đã thử viết một script Python nhỏ để tự động hóa việc này.
Ý tưởng là script sẽ duyệt qua một thư mục được chỉ định, sau đó lấy thông tin của tất cả các file ảnh (ví dụ: .jpg, .png) trong đó và xuất ra một file Excel. Thông tin bao gồm:
- Tên file
- Định dạng file
- Kích thước (bytes)
- Ngày tạo
- Ngày sửa đổi gần nhất
Script này khá đơn giản, sử dụng thư viện os để duyệt thư mục và lấy thông tin file, cùng với thư viện pandas để tạo và xuất ra file Excel.
Dưới đây là đoạn code mẫu:
import os
import pandas as pd
from datetime import datetime
def get_image_info(folder_path):
data = []
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path) and filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
try:
file_size = os.path.getsize(file_path)
creation_time_ts = os.path.getctime(file_path)
modification_time_ts = os.path.getmtime(file_path)
creation_time = datetime.fromtimestamp(creation_time_ts).strftime('%Y-%m-%d %H:%M:%S')
modification_time = datetime.fromtimestamp(modification_time_ts).strftime('%Y-%m-%d %H:%M:%S')
data.append({
'Tên file': filename,
'Định dạng': os.path.splitext(filename)[1],
'Kích thước (bytes)': file_size,
'Ngày tạo': creation_time,
'Ngày sửa đổi': modification_time
})
except Exception as e:
print(f"Lỗi khi xử lý file {filename}: {e}")
return pd.DataFrame(data)
# --- Sử dụng ---
folder_to_scan = "/path/to/your/image/folder" # Thay đổi đường dẫn này
output_excel_file = "danh_sach_anh.xlsx"
image_df = get_image_info(folder_to_scan)
if not image_df.empty:
image_df.to_excel(output_excel_file, index=False)
print(f"Đã xuất danh sách ảnh ra file {output_excel_file}")
else:
print("Không tìm thấy file ảnh nào trong thư mục.")
Mọi người nhớ thay thế "/path/to/your/image/folder" bằng đường dẫn thư mục chứa ảnh của mình nhé.
Hy vọng script này hữu ích cho ai đó đang cần xử lý danh sách ảnh một cách nhanh chóng. Có thắc mắc gì cứ hỏi mình.