Naposledy aktivní 9 months ago

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

timmy revidoval tento gist 9 months ago. Přejít na revizi

1 file changed, 23 insertions

shutil_example.py(vytvořil soubor)

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