用Python掃描目錄,輕鬆整理數據!

Ai




DIY AI 第六部分:使用 Python 繪製目錄以實現高效數據組織

如果你一直在關注我們的 DIY AI 項目,你應該已經準備好你的排程腳本,現在我們將使用它開始收集數據,這些數據將用來訓練我們正在創建的 AI。這次的任務是掃描目錄以獲取文件元數據,這是許多 AI 應用的基本功能。

為什麼要掃描目錄以獲取元數據?
有關文件的元數據,例如大小、修改日期和文件類型,通常是進行數據分析、機器學習預處理或系統監控等高級功能的起點。這些信息可以幫助 AI 找到文件、整理文件等。

一開始,腳本僅會掃描你的桌面,因為這是許多人電腦上最活躍的地方,並且這樣可以幫助整理。不過,你可以輕鬆更改以掃描任何文件,甚至可以掃描整個硬碟,但這會消耗大量資源。一旦腳本掃描了驅動器,它將創建一個日誌,當你有足夠的日誌後,就可以進入下一步,稍後我們會討論這一步。

逐步解析腳本
讓我們開始逐步解析腳本,看看它是如何工作的。然後,我會粘貼整個代碼,讓你可以複製和粘貼。如果你還沒有閱讀之前的指南,建議你先確保你已經跟上進度,並擁有繼續所需的一切。

導入必要的庫
你應該已經安裝了所有需要的庫,但仍需導入它們。

– `os` 將幫助你在目錄中移動並獲取文件信息。
– `pandas` 將數據組織成 DataFrame,便於處理。
– `pathlib` 簡化文件和路徑操作。
– `datetime` 生成可讀的時間戳。

“`python
import os
import pandas as pd
from pathlib import Path
from datetime import datetime
“`

創建 scan_directory 函數
這個函數執行掃描目錄和收集元數據的核心任務。它將遍歷目錄及任何子目錄,檢索文件的大小以及最後修改時間,然後將時間戳轉換為可讀的日期格式。

“`python
def scan_directory(directory: Path) -> pd.DataFrame:
paths, names, extensions, sizes, modified_times = [], [], [], [], []

for root, dirs, files in os.walk(directory):
for filename in files:
file_path = Path(root) / filename
paths.append(str(file_path))
names.append(file_path.stem)
extensions.append(file_path.suffix)
sizes.append(file_path.stat().st_size)
mod_time = file_path.stat().st_mtime
modified_times.append(datetime.fromtimestamp(mod_time))

return pd.DataFrame({
“path”: paths,
“name”: names,
“extension”: extensions,
“size_bytes”: sizes,
“last_modified”: modified_times
})
“`

定義腳本的主要工作流程
這段代碼告訴腳本應該掃描哪個目錄,並打印出它找到的前幾行,以便你知道它正在運行,因為如果桌面上有很多文件和文件夾,這可能需要一些時間來完成。你可以更改這個設置,以掃描任何目錄。

“`python
if __name__ == “__main__”:
directory_to_scan = Path.home() / “Desktop” # 掃描用戶的桌面
file_df = scan_directory(directory_to_scan) # 調用函數
print(file_df.head()) # 顯示前幾行以確認運行正常
“`

將文件與時間戳保存在正確的文件夾中
這段代碼將我們的數據保存到 CSV 文件中,文件名中包含時間戳,因此每次運行時,AI 都可以將新文件與其他文件進行比較。然後將文件放在名為 Directory_Mapper_Data 的文件夾中。

“`python
project_root = Path(__file__).resolve().parent.parent
data_dir = project_root / “data”
directory_mapper_dir = data_dir / “Directory_Mapper_Data”
directory_mapper_dir.mkdir(parents=True, exist_ok=True) # 如果缺少文件夾則創建

timestamp = datetime.now().strftime(“%Y%m%d_%H%M%S”) # 生成唯一時間戳
output_filename = f”desktop_files_metadata_{timestamp}.csv”
output_path = directory_mapper_dir / output_filename

file_df.to_csv(output_path, index=False) # 將 DataFrame 保存為 CSV
print(f”文件元數據已保存到 {output_path}”)
“`

完整的 directory_scanner.py 腳本
“`python
import os
import pandas as pd
from pathlib import Path
from datetime import datetime

def scan_directory(directory: Path) -> pd.DataFrame:
paths, names, extensions, sizes, modified_times = [], [], [], [], []

for root, dirs, files in os.walk(directory):
for filename in files:
file_path = Path(root) / filename
paths.append(str(file_path))
names.append(file_path.stem)
extensions.append(file_path.suffix)
sizes.append(file_path.stat().st_size)
mod_time = file_path.stat().st_mtime
modified_times.append(datetime.fromtimestamp(mod_time))

return pd.DataFrame({
“path”: paths,
“name”: names,
“extension”: extensions,
“size_bytes”: sizes,
“last_modified”: modified_times
})

if __name__ == “__main__”:
directory_to_scan = Path.home() / “Desktop”
file_df = scan_directory(directory_to_scan)
print(file_df.head())

project_root = Path(__file__).resolve().parent.parent
data_dir = project_root / “data”
directory_mapper_dir = data_dir / “Directory_Mapper_Data”
directory_mapper_dir.mkdir(parents=True, exist_ok=True)

timestamp = datetime.now().strftime(“%Y%m%d_%H%M%S”)
output_filename = f”desktop_files_metadata_{timestamp}.csv”
output_path = directory_mapper_dir / output_filename

file_df.to_csv(output_path, index=False)
print(f”文件元數據已保存到 {output_path}”)
“`

接下來的步驟是什麼?
將腳本添加到你的項目中,運行它以確保它能掃描目錄並在正確的文件夾中創建保存的文件。然後,將其添加到我們上次創建的排程器中,讓它每天運行一次。根據你的文件變化頻率,可以選擇每天運行更多或更少。

我們需要這個新腳本收集數據至少幾天。一旦我們擁有了一些良好的數據,就可以開始為機器學習做準備。下一篇指南中將進一步討論這方面的內容。

在這個過程中,通過數據的收集和整理,我們可以更深入地理解如何利用 AI 來分析和處理信息。這種技能不僅對於開發 AI 系統至關重要,也能幫助我們在日常工作中提高效率和組織能力。隨著我們進一步探索 AI 和 Python 編程的世界,未來的可能性將是無限的。

以上文章由特價GPT API KEY所翻譯及撰寫。而圖片則由FLUX根據內容自動生成。

🎬 YouTube Premium 家庭 Plan成員一位 只需 HK$148/年

不用提供密碼、不用VPN、無需轉區
直接升級你的香港帳號 ➜ 即享 YouTube + YouTube Music 無廣告播放

立即升級 🔗

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

🎨 Nano Banana Pro 圖像生成器|打幾句說話就出圖

想畫人像、產品圖、插畫?SSFuture 圖像生成器支援 Flux Gemini Nano Banana Pro 改圖 / 合成, 打廣東話都得,仲可以沿用上一張圖繼續微調。

🆓 Flux 模型即玩,不用登入
🤖 登入後解鎖 Gemini 改圖
📷 支援上載參考圖再生成
⚡ 每天免費額度任你玩
✨ 即刻玩 AI 畫圖
Ultra-realistic, vibrant aerial adventure photograph captures a joyful man (same face as reference image, 100% accuracy) paragliding high above a breathtaking tropical coastline. He is seated comfortably in his black and orange harness, legs dangling freely, facing the camera with a wide, excited smile, teeth showing, conveying pure exhilaration. He sports dark brown hair and a light beard,wearing a bright red t-shirt emblazoned with 'style' in bold white text within a blackCteate a Ultra-realistic, vibrant aerial adventure photograph in 9:16 ratio captures a joyful man (same face as reference image, 100% accuracy) paragliding high above a breathtaking tropical coastline. He is seated comfortably in his black and orange harness, legs dangling freely, facing the camera with a wide, excited smile, teeth showing, conveying pure exhilaration. He sports dark brown hair and a light beard,wearing a bright red t-shirt emblazoned with 'style' in bold white text within a blackrectangle, layered beneath an open blue and black plaid long-sleeved shirt. His attire includes grey cargo shorts, white socks, and distinctive red, white, and black high-top sneakers. In his left hand, he holds a black selfie stick, while his right grasps the paragliding control lines. The stunning backdrop features crystal-clear turquoise and deep blue ocean revealing intricate coral reefs and gentle breaking waves near a pristine white sandy beach. A charming coastal town with numerouswhite buildings is nestled against lush, emerald-green, tree-covered hills, which ascend to distant, hazy mountains under a softly clouded sky. Another yellow paraglider gracefully soars in the distance, and a long concrete pier extends into the tranquil water. The scene is illuminated by bright, diffused natural light, creating an exhilarating, free-spirited, and idyllic tropical mood, with a color palette dominated by vivid turquoises, deep blues, and verdant greens, beautifully contrastedby the crisp whites of the beach and town, and the bold reds of his clothing and footwear. add lotso and hamm Create a hyper-realistic promo image using my uploaded photo.  
Keep my real face exactly as it is (no changes to eyes, mouth, jawline, or skin).  
Place my portrait seamlessly inside the design of the US 100-dollar bill, maintaining the texture and engraving lines.  
Add two more versions:  
- One on the Euro (€100) banknote  
- One on the British Pound (£50) banknote  
Ensure the portrait blends naturally with the currency engraving style, with deep shadows, embossed effect, and authentic banknote detailing.  
Ultra HD, crisp details, cinematic lighting, clean background, premium quality