
🔧 功能說明
這支程式的功能包括:
- 讀取指定資料夾中所有 PDF 檔案
- 透過
pdftk
工具讀取每個 PDF 的頁數 - 取得檔案大小、建立與修改時間
- 將成功與失敗的分析結果,分別整理為兩張 Excel 工作表
- 將結果儲存到桌面的 Excel 檔中
🖥️ 使用方式
- 開啟命令列(例如 Terminal 或 Anaconda Prompt)
- 執行這支 Python 檔案
- 輸入欲分析的資料夾路徑,例如:
請輸入來源資料夾路徑:"D:\MyPDFs"
- 等待進度列顯示分析過程(使用
tqdm
) - 程式完成後,會在桌面上產生一個名為
PDF頁數分析_年月日時分秒.xlsx
的 Excel 檔案,內含:PDF分析結果
:成功讀取頁數與資訊的檔案失敗清單
:無法處理的 PDF(例如損壞或加密)
需要安裝的庫
pip install PyPDF2 tqdm pandas openpyxl
程式碼
import os
import PyPDF2
import pandas as pd
from datetime import datetime
from pathlib import Path
from tqdm import tqdm
# 詢問來源資料夾
source_dir = input("請輸入來源資料夾路徑:").strip('"').strip("'")
# 確認來源資料夾存在
if not os.path.isdir(source_dir):
print("❌ 資料夾不存在,請檢查路徑。")
exit(1)
# 搜集所有 PDF 檔案(先建立清單再跑 tqdm)
pdf_files = []
for root, dirs, files in os.walk(source_dir):
for file in files:
if file.lower().endswith(".pdf"):
pdf_files.append((root, file))
# 收集成功與失敗資料
success_data = []
failed_list = []
# tqdm 顯示進度
for root, file in tqdm(pdf_files, desc="分析中", unit="檔案"):
full_path = os.path.join(root, file)
folder_name = os.path.basename(root)
folder_path = os.path.join(root, '') # 保留尾端斜線
file_name = file
file_stem = os.path.splitext(file)[0]
# 預設頁數為 None
num_pages = None
try:
# 使用 PyPDF2 讀取 PDF 頁數
with open(full_path, "rb") as f:
pdf_reader = PyPDF2.PdfReader(f)
num_pages = len(pdf_reader.pages)
except Exception:
pass # 略過錯誤處理,改在下方記錄
if num_pages is None:
failed_list.append(full_path)
continue
# 容量(MB)
try:
size_mb = round(os.path.getsize(full_path) / (1024 * 1024), 2)
except:
size_mb = None
# 建立與修改時間
try:
created_time = datetime.fromtimestamp(os.path.getctime(full_path)).strftime('%Y-%m-%d %H:%M:%S')
modified_time = datetime.fromtimestamp(os.path.getmtime(full_path)).strftime('%Y-%m-%d %H:%M:%S')
except:
created_time = modified_time = None
# 加入成功清單
success_data.append([
full_path,
folder_name,
folder_path,
file_name,
file_stem,
num_pages,
size_mb,
created_time,
modified_time
])
# 建立 DataFrame
columns = [
"PDF完整路徑",
"所在資料夾名稱",
"所在資料夾路徑(包含結尾斜線)",
"檔名含副檔名",
"檔名不含副檔名",
"頁數",
"容量(MB)",
"建立日期",
"修改日期"
]
df_success = pd.DataFrame(success_data, columns=columns)
df_failed = pd.DataFrame(failed_list, columns=["無法分析的PDF路徑"])
# 匯出 Excel
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
desktop = Path.home() / "Desktop"
output_file = desktop / f"PDF頁數分析_{timestamp}.xlsx"
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
df_success.to_excel(writer, sheet_name='PDF分析結果', index=False)
df_failed.to_excel(writer, sheet_name='失敗清單', index=False)
print(f"\n✅ 已匯出:{output_file}")
Tags
泉製作所