timmy zrewidował ten Gist 9 months ago. Przejdź do rewizji
1 file changed, 23 insertions
shutil_example.py(stworzono plik)
| @@ -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}") | |
Nowsze
Starsze