Python | Move or Copy Files and Directories

Last Updated : 3 Feb, 2026

Python provides the shutil module to copy or move files and directories without relying on shell commands. The shutil module offers high-level file operations, making it easy to copy, move, and delete files and directories programmatically.

Methods provided by shutil library

  1. shutil.copy(src, dst): Copies a file from source to destination. Copies file data and permission bits, but not full metadata like timestamps.
  2. shutil.copy2(src, dst): Copies a file along with most metadata (modification time, access time, permissions). Ownership and ACLs may not be preserved depending on OS.
  3. shutil.copytree(src, dst, dirs_exist_ok=False): Recursively copies an entire directory including all subfolders and files. By default, destination must not already exist.
  4. shutil.move(src, dst): Moves a file or directory. Uses rename when possible, otherwise performs copy + delete.
  5. shutil.rmtree(path): Deletes a directory and all its contents recursively.

Note: src and dst are the source and destination paths, respectively.

By default, copy operations follow symbolic links and copy the target file.To copy the link itself instead of the target, use the following options.

Python
shutil.copy2(src, dst, follow_symlinks=False)
shutil.copytree(src, dst, symlinks=True)

Ignoring Certain Files

copytree() function allows excluding specific files or directories during the copy process using an ignore function.

Using Custom Ignore Function

Python
# defining custom ignore function
def ignore_pyc_files(dirname, filenames):
    return [name for name in filenames if name.endswith('.pyc')]

shutil.copytree(src, dst, ignore=ignore_pyc_files)

Using Built-in Ignore Patterns

Python's shutil.copytree() can copy entire directories, but sometimes you may want to skip certain files (e.g., temporary files or compiled Python files). You can use shutil.ignore_patterns() to ignore files that match specific patterns.

shutil.copytree(src, dst, ignore=shutil.ignore_patterns('*~', '*.pyc'))

How shutil Copy Works:

  • shutil functions emulate Unix commands.
  • copy2() preserves metadata such as access times, creation times, and permissions.
  • Extended metadata (owners, ACLs, resource forks) may not always be preserved depending on OS and user permissions.
  • copytree() is not recommended for system backups

Working with File Paths

When working with files, handling paths correctly is important for portability across different operating systems.

1. Using pathlib: pathlib provides an object-oriented way to work with paths:

Python
from pathlib import Path

p = Path("folder/file.txt")
print(p.name)
print(p.parent)

Explanation:

  • p = Path("folder/file.txt"): Creates a Path object representing the path folder/file.txt. No file access happens here; it just builds a path object.
  • print(p.name): Prints the final component of the path (the file name). Output: file.txt
  • print(p.parent): Prints the parent directory of the path. Output: folder

2. Using os.path: Python’s os.path module provides utility functions to manipulate file and directory paths safely and efficiently.

Python
import os.path

filename = 'your_file_name.py'

os.path.basename(filename)
os.path.dirname(filename)
os.path.split(filename)
os.path.join('/new/dir', os.path.basename(filename))
os.path.expanduser('~/gfg/programs/abc.py')

Explanation:

  • os.path.basename(filename): Returns the file name from the given path.
  • os.path.dirname(filename): Returns the directory path of the given file.
  • os.path.split(filename): Splits the path into a tuple (directory, filename).
  • os.path.join('/new/dir', os.path.basename(filename)): Joins the directory path with the file name to create a new file path.
  • os.path.expanduser('~/gfg/programs/abc.py'): Expands ~ to the user’s home directory, giving the full absolute path.

Handling Errors in copytree()

While copying directories using shutil.copytree(), errors such as missing files or permission issues may occur. These can be handled using try-except blocks.

Python
import shutil

try:
    shutil.copytree('source_dir', 'destination_dir')
except Exception as e:
    print("Error occurred while copying:", e)

Explanation:

  • shutil.copytree() attempts to copy the entire directory.
  • If an error occurs (e.g., permission denied or file not found), an exception is raised.
  • try-except block catches the error and prevents the program from crashing.
Comment