除了文字檔案的讀寫,實際應用中我們常常要處理一整個資料夾的內容,例如整理圖片、批次更名、備份檔案,Python 提供了 os 與 shutil 模組,能讓我們像在檔案總管裡操作一樣,直接用程式來管理檔案。
import os
print(os.getcwd()) # 目前工作路徑
os.mkdir("test_folder") # 建立資料夾
print("建立成功!")
print(os.path.exists("test_folder")) # 檢查是否存在
print(os.path.isfile("notes.txt")) # 是否是檔案
print(os.path.isdir("test_folder")) # 是否是資料夾
files = os.listdir(".") # 列出當前路徑下的所有檔案與資料夾
print(files)
import shutil
# 檔案更名
os.rename("notes.txt", "my_notes.txt")
# 複製檔案
shutil.copy("my_notes.txt", "backup_notes.txt")
# 移動檔案
shutil.move("backup_notes.txt", "test_folder/")
# 刪除檔案
os.remove("my_notes.txt")
# 刪除資料夾
os.rmdir("test_folder") # 資料夾必須是空的
請寫一個「自動整理資料夾」程式:
這個挑戰能讓你練習 os 與 shutil 的操作,並體驗到 Python 幫你「自動化生活」的威力。
--- by Ricky