Using Python’s shutil Module for File and Directory Operations
This article introduces Python’s shutil module and demonstrates how to copy, move, rename, archive, and delete files and directories with concise code examples while highlighting important safety considerations.
shutil is a Python standard library module that provides high‑level file operations such as copying, moving, renaming, and archiving.
1. Copy a file – Use
import shutil
shutil.copy('source_file.txt', 'destination_folder/source_file_copy.txt')
print("文件已复制")to copy a file and optionally set its permission mode.
2. Move or rename a file/directory –
import shutil
shutil.move('old_location/file.txt', 'new_location/new_filename.txt')
print("文件已移动或重命名")moves or renames the target.
3. Copy an entire directory tree –
import shutil
shutil.copytree('source_directory', 'destination_directory')
print("目录已复制")recursively copies a directory and its contents.
4. Delete an entire directory tree –
import shutil
shutil.rmtree('directory_to_remove')
print("目录已被删除")removes a directory and all its sub‑files permanently.
5. Create a ZIP archive –
import shutil
archive_name = shutil.make_archive('backup', 'zip', 'source_directory')
print(f"归档已创建: {archive_name}")creates a zip (or tar) archive of a directory.
6. Extract a ZIP archive –
import shutil
shutil.unpack_archive('example.zip', 'extract_directory')
print("文件已解压")extracts the archive to a target folder.
When performing operations that may overwrite existing files, back up important data; use shutil.rmtree() with extreme caution because it permanently deletes everything in the specified path, and ensure you have appropriate read/write permissions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
