Site Tools


import-shutil

import shutil

import shutil is a Python import that provides high-level file operations: copying, moving, removing directory trees, and archiving files.

Example

# Python
# description: copy files, remove directories, create archives
 
import shutil
import os
 
# Copy file
shutil.copy("source.txt", "destination.txt")
 
# Copy file with metadata
shutil.copy2("source.txt", "destination.txt")
 
# Copy entire directory tree
shutil.copytree("src_dir", "dst_dir")
 
# Move file or directory
shutil.move("old_name.txt", "new_name.txt")
 
# Remove entire directory tree
shutil.rmtree("directory_to_delete")
 
# Create tar archive
shutil.make_archive("backup", "tar", base_dir="data")
 
# Extract archive
shutil.unpack_archive("backup.tar", extract_dir="restored")
 
# Get disk usage
usage = shutil.disk_usage("/")
print(f"Total: {usage.total}, Used: {usage.used}, Free: {usage.free}")

Common functions

  • shutil.copy(src, dst): copy file
  • shutil.copy2(src, dst): copy with metadata
  • shutil.copytree(src, dst): copy directory tree
  • shutil.move(src, dst): move file or directory
  • shutil.rmtree(path): remove directory tree
  • shutil.make_archive(base, format, base_dir): create archive
  • shutil.unpack_archive(filename, extract_dir): extract archive
  • shutil.disk_usage(path): get disk usage
import-shutil.md · Last modified: by 127.0.0.1