shutil_example.py
· 617 B · Python
Originalformat
import shutil
import os
# 定義來源與目標
source_file = "example.txt"
destination_dir = "backup/"
destination_file = os.path.join(destination_dir, source_file)
# 確保目標目錄存在
os.makedirs(destination_dir, exist_ok=True)
# 複製檔案
shutil.copy(source_file, destination_file)
print(f"已複製 {source_file} 到 {destination_file}")
# 移動檔案
new_location = "moved_example.txt"
shutil.move(destination_file, new_location)
print(f"已移動 {destination_file} 到 {new_location}")
# 刪除目錄(小心使用)
shutil.rmtree(destination_dir)
print(f"已刪除目錄 {destination_dir}")
| 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}") |
| 24 |