在Python中,你可以使用os
和shutil
庫來執行磁盤清理任務
import os
import shutil
def clean_disk(path):
# 列出指定路徑下的所有文件和文件夾
for root, dirs, files in os.walk(path):
for file in files:
# 刪除文件
file_path = os.path.join(root, file)
try:
os.remove(file_path)
print(f"已刪除文件: {file_path}")
except OSError as e:
print(f"無法刪除文件 {file_path}: {e}")
for dir in dirs:
# 刪除空文件夾
dir_path = os.path.join(root, dir)
try:
shutil.rmtree(dir_path)
print(f"已刪除空文件夾: {dir_path}")
except OSError as e:
print(f"無法刪除空文件夾 {dir_path}: {e}")
# 調用函數,傳入要清理的路徑
clean_disk("/path/to/your/directory")
請注意,這個示例會刪除指定路徑下的所有文件和空文件夾。你可以根據需要修改clean_disk
函數來實現更復雜的清理邏輯。在執行磁盤清理之前,請確保你了解這些操作的影響,并在一個安全的環境中進行測試。