Utoljára aktív 9 months ago

shutil 模組提供高級的檔案與目錄管理功能,包括複製、移動、壓縮與刪除,適用於備份、部署與自動化檔案管理。

Revízió 5deb981f29e07ed6f64f5dec16c430b0e63c5a4d

shutil_example.py Eredeti
1import shutil
2import os
3
4# 定義來源與目標
5source_file = "example.txt"
6destination_dir = "backup/"
7destination_file = os.path.join(destination_dir, source_file)
8
9# 確保目標目錄存在
10os.makedirs(destination_dir, exist_ok=True)
11
12# 複製檔案
13shutil.copy(source_file, destination_file)
14print(f"已複製 {source_file}{destination_file}")
15
16# 移動檔案
17new_location = "moved_example.txt"
18shutil.move(destination_file, new_location)
19print(f"已移動 {destination_file}{new_location}")
20
21# 刪除目錄(小心使用)
22shutil.rmtree(destination_dir)
23print(f"已刪除目錄 {destination_dir}")
24