Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Copy File

Python Copy File - Complete Guide

Learn how to copy files in Python using the shutil module.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Copying Files in Python
  • shutil.copy()
  • shutil.copy2()
  • shutil.copyfile()
  • copy() vs copy2()
  • Batch Copying Files
  • Error Handling
  • Best Practices
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • shutil.copy() — copy file with permissions
  • shutil.copy2() — copy with metadata
  • shutil.copyfile() — copy file content only
  • copy() vs copy2() — understanding the difference
  • Batch copying — copying multiple files
  • Error handling — robust file copying

Copying Files in Python

Copying files is a common operation when you need to create backups, duplicate data, or organize files. Python's shutil module provides several functions to copy files, each with different features.

Think of copying a file like making a photocopy of a document. The original stays untouched, and you get an exact duplicate. Python gives you several ways to make these copies, depending on what you need to preserve.

💡 Key concept: The shutil module (shell utilities) provides high-level file operations. For copying files, it offers three main functions: copy(), copy2(), and copyfile(). Each serves a different purpose.

shutil.copy()

1

Copy with Permissions

# The shutil.copy() function copies the file and its permissions

import shutil
import os

# Create a sample file
with open("original.txt", "w") as f:
    f.write("This is the original file.\n")
    f.write("We will copy this file.\n")

# 1. Basic copy
shutil.copy("original.txt", "copy.txt")
print("Copied: original.txt → copy.txt")

# 2. Copy to a different directory
# First create a directory
os.makedirs("backup", exist_ok=True)
shutil.copy("original.txt", "backup/original.txt")
print("Copied: original.txt → backup/original.txt")

# 3. Copy with a new name in a different directory
shutil.copy("original.txt", "backup/backup_copy.txt")
print("Copied: original.txt → backup/backup_copy.txt")

# 4. Verify the copy
with open("copy.txt", "r") as f:
    content = f.read()
    print("Content of copy.txt:")
    print(content)

# 5. Check permissions
import stat
original_perms = os.stat("original.txt").st_mode
copy_perms = os.stat("copy.txt").st_mode
print(f"Original permissions: {oct(original_perms)}")
print(f"Copy permissions: {oct(copy_perms)}")

shutil.copy() key points:

  • Copies content — file content is duplicated
  • Copies permissions — file permissions are preserved
  • Destination can be directory — copies with same name
  • Destination can be file — copies with new name
  • Returns path — returns the path to the copied file

Quick Check: What does shutil.copy() preserve? (Answer: File content and permissions)

shutil.copy2()

2

Copy with All Metadata

# shutil.copy2() copies the file with all metadata

import shutil
import os
import time

# Create a file with specific metadata
with open("source.txt", "w") as f:
    f.write("This file has metadata.\n")
    f.write("We'll copy it with copy2().\n")

# Get original metadata
original_stat = os.stat("source.txt")
print(f"Original last modified: {time.ctime(original_stat.st_mtime)}")

# Wait a moment to ensure timestamps differ
time.sleep(1)

# Copy with copy2()
shutil.copy2("source.txt", "metadata_copy.txt")
print("Copied: source.txt → metadata_copy.txt")

# Check copied metadata
copy_stat = os.stat("metadata_copy.txt")
print(f"Copy last modified: {time.ctime(copy_stat.st_mtime)}")

# Compare with shutil.copy()
shutil.copy("source.txt", "simple_copy.txt")
simple_stat = os.stat("simple_copy.txt")
print(f"Simple copy last modified: {time.ctime(simple_stat.st_mtime)}")

# copy2() preserves timestamps, copy() does not

shutil.copy2() key points:

  • Copies all metadata — timestamps, permissions, etc.
  • Preserves timestamps — creation and modification times
  • More complete — best for exact duplicates
  • Slightly slower — due to copying extra metadata

Quick Check: What additional metadata does copy2() preserve? (Answer: Timestamps and file metadata)

shutil.copyfile()

3

Copy File Content Only

# shutil.copyfile() copies only the file content

import shutil

# Create a source file
with open("source_data.txt", "w") as f:
    f.write("This file contains important data.\n")
    f.write("We'll copy the content only.\n")

# 1. Basic copyfile
shutil.copyfile("source_data.txt", "content_copy.txt")
print("Copied content: source_data.txt → content_copy.txt")

# 2. Verify content
with open("content_copy.txt", "r") as f:
    content = f.read()
    print("Content of copy:")
    print(content)

# 3. copyfile() requires the destination to be a file
# It cannot copy to a directory

# 4. Check if files are identical
import filecmp
if filecmp.cmp("source_data.txt", "content_copy.txt"):
    print("Files are identical!")
else:
    print("Files are different!")

# 5. copyfile() vs copy()
# copyfile() - only content
# copy() - content + permissions

shutil.copyfile() key points:

  • Content only — copies file content only
  • No metadata — does not preserve permissions or timestamps
  • Destination must be file — cannot copy to a directory
  • Fastest method — least overhead

Quick Check: What does shutil.copyfile() copy? (Answer: Only the file content)

copy() vs copy2()

4

Choosing the Right Copy Function

# Comparison of copy functions

import shutil
import os
import time

# Create a test file
with open("test.txt", "w") as f:
    f.write("Test file for comparing copy methods.\n")
    f.write("We'll see the differences in metadata preservation.\n")

# Get original metadata
orig_stat = os.stat("test.txt")
print("=== Original File ===")
print(f"Size: {orig_stat.st_size} bytes")
print(f"Last modified: {time.ctime(orig_stat.st_mtime)}")
print(f"Permissions: {oct(orig_stat.st_mode)}\n")

# Wait to ensure timestamps differ
time.sleep(1)

# Copy using different methods
shutil.copy("test.txt", "copy_method.txt")
shutil.copy2("test.txt", "copy2_method.txt")
shutil.copyfile("test.txt", "copyfile_method.txt")

print("=== After Copying ===")

# Check copy() result
copy_stat = os.stat("copy_method.txt")
print("1. shutil.copy()")
print(f"   Size: {copy_stat.st_size} bytes")
print(f"   Modified: {time.ctime(copy_stat.st_mtime)}")
print(f"   Permissions: {oct(copy_stat.st_mode)}\n")

# Check copy2() result
copy2_stat = os.stat("copy2_method.txt")
print("2. shutil.copy2()")
print(f"   Size: {copy2_stat.st_size} bytes")
print(f"   Modified: {time.ctime(copy2_stat.st_mtime)}")
print(f"   Permissions: {oct(copy2_stat.st_mode)}\n")

# Check copyfile() result
copyfile_stat = os.stat("copyfile_method.txt")
print("3. shutil.copyfile()")
print(f"   Size: {copyfile_stat.st_size} bytes")
print(f"   Modified: {time.ctime(copyfile_stat.st_mtime)}")
print(f"   Permissions: {oct(copyfile_stat.st_mode)}")

print("\n=== Summary ===")
print("copy() - copies content + permissions")
print("copy2() - copies content + permissions + timestamps")
print("copyfile() - copies content only")

Comparison summary:

  • copy() — content + permissions (best for backups)
  • copy2() — content + permissions + timestamps (exact duplicate)
  • copyfile() — content only (fastest)

Quick Check: Which function creates the most complete copy? (Answer: shutil.copy2())

Batch Copying Files

5

Copying Multiple Files

import shutil
import os

# Create sample files
for i in range(3):
    with open(f"file_{i}.txt", "w") as f:
        f.write(f"Sample file {i}\n")
        f.write("Created for batch copy demonstration.\n")

# 1. Copy all files in a directory to a backup folder
def backup_files(source_dir, backup_dir):
    """Copy all files from source to backup directory"""
    os.makedirs(backup_dir, exist_ok=True)
    
    for filename in os.listdir(source_dir):
        source_path = os.path.join(source_dir, filename)
        if os.path.isfile(source_path):
            dest_path = os.path.join(backup_dir, filename)
            shutil.copy2(source_path, dest_path)
            print(f"Copied: {filename} → {backup_dir}/")

backup_files(".", "backup_files")

# 2. Copy files matching a pattern
def copy_matching_files(source_dir, dest_dir, pattern):
    """Copy files matching a pattern"""
    os.makedirs(dest_dir, exist_ok=True)
    
    for filename in os.listdir(source_dir):
        if pattern in filename and os.path.isfile(os.path.join(source_dir, filename)):
            source_path = os.path.join(source_dir, filename)
            dest_path = os.path.join(dest_dir, filename)
            shutil.copy2(source_path, dest_path)
            print(f"Copied: {filename} → {dest_dir}/")

copy_matching_files(".", "pattern_files", "file_")

# 3. Copy with progress tracking
def copy_with_progress(source, dest):
    """Copy a file with progress indication"""
    import time
    
    source_size = os.path.getsize(source)
    copied = 0
    
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        while True:
            chunk = src.read(1024 * 1024)  # 1MB chunks
            if not chunk:
                break
            dst.write(chunk)
            copied += len(chunk)
            progress = (copied / source_size) * 100
            print(f"Progress: {progress:.1f}%", end='\r')
    
    print()  # New line after progress
    print(f"Copy complete: {source} → {dest}")

# 4. Copy with verification
def copy_with_verification(source, dest):
    """Copy and verify the file was copied correctly"""
    shutil.copy2(source, dest)
    
    import filecmp
    if filecmp.cmp(source, dest):
        print(f"✅ Verified: {source} and {dest} are identical")
        return True
    else:
        print(f"❌ Verification failed: {source} and {dest} differ")
        return False

Batch copying strategies:

  • All files — copy every file in a directory
  • Pattern matching — copy only files matching a pattern
  • Progress tracking — monitor copy progress
  • Verification — confirm files were copied correctly

Quick Check: Why would you verify a file after copying? (Answer: To ensure the copy was successful and accurate)

Error Handling When Copying

6

Robust File Copying

import shutil
import os

# 1. Comprehensive copy function
def safe_copy(source, destination):
    """Safely copy a file with error handling"""
    try:
        # Check if source exists
        if not os.path.exists(source):
            print(f"Error: Source '{source}' does not exist")
            return False
        
        # Check if source is a file
        if not os.path.isfile(source):
            print(f"Error: '{source}' is not a file")
            return False
        
        # Check if destination directory exists
        dest_dir = os.path.dirname(destination)
        if dest_dir and not os.path.exists(dest_dir):
            os.makedirs(dest_dir, exist_ok=True)
            print(f"Created directory: {dest_dir}")
        
        # Perform the copy
        shutil.copy2(source, destination)
        print(f"Copied: {source} → {destination}")
        return True
    
    except PermissionError:
        print(f"Error: Permission denied when copying '{source}'")
        return False
    
    except OSError as e:
        print(f"Error: {e}")
        return False
    
    except Exception as e:
        print(f"Unexpected error: {e}")
        return False

# 2. Copy with automatic backup
def copy_with_backup(source, destination):
    """Copy a file with automatic backup of existing file"""
    if os.path.exists(destination):
        backup = destination + ".backup"
        shutil.copy2(destination, backup)
        print(f"Existing file backed up as: {backup}")
    
    return safe_copy(source, destination)

# 3. Copy with confirmation
def copy_with_confirm(source, destination):
    """Copy a file with user confirmation"""
    if os.path.exists(destination):
        print(f"Warning: '{destination}' already exists")
        response = input("Overwrite? (y/n): ")
        if response.lower() != 'y':
            print("Copy cancelled")
            return False
    
    return safe_copy(source, destination)

Common copy errors:

  • FileNotFoundError — source file doesn't exist
  • PermissionError — can't read source or write destination
  • IsADirectoryError — trying to copy a directory as a file
  • Always handle errors — make your code robust

Quick Check: What error occurs when you try to copy a file you don't have permission to read? (Answer: PermissionError)

Best Practices for Copying Files

7

Professional File Copying Guidelines

import shutil
import os

# 1. Always check if source exists
def smart_copy(source, destination):
    """Copy with existence checks"""
    if not os.path.exists(source):
        print(f"Cannot copy: '{source}' does not exist")
        return False
    
    if os.path.exists(destination):
        print(f"Warning: '{destination}' will be overwritten")
    
    try:
        shutil.copy2(source, destination)
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

# 2. Use the right copy function
# For backups: shutil.copy2() - preserves everything
# For quick copies: shutil.copy() - preserves permissions
# For content only: shutil.copyfile() - fastest

# 3. Create destination directories if needed
def copy_with_dirs(source, destination):
    """Copy and create destination directory if needed"""
    dest_dir = os.path.dirname(destination)
    if dest_dir and not os.path.exists(dest_dir):
        os.makedirs(dest_dir, exist_ok=True)
        print(f"Created directory: {dest_dir}")
    
    return smart_copy(source, destination)

# 4. Use filecmp for verification
def verified_copy(source, destination):
    """Copy and verify the result"""
    if smart_copy(source, destination):
        import filecmp
        if filecmp.cmp(source, destination):
            print(f"Copy verified: {source} and {destination} match")
            return True
        else:
            print(f"Warning: Copy verification failed for {destination}")
            return False
    return False

# 5. Copy large files efficiently
def copy_large_file(source, destination):
    """Copy large files in chunks to save memory"""
    try:
        with open(source, 'rb') as src, open(destination, 'wb') as dst:
            while True:
                chunk = src.read(1024 * 1024)  # 1MB chunks
                if not chunk:
                    break
                dst.write(chunk)
        print(f"Copy complete: {source} → {destination}")
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

Best practices summary:

  • Check source — verify file exists before copying
  • Use right function — copy(), copy2(), or copyfile()
  • Create directories — ensure destination exists
  • Verify copies — confirm files are identical
  • Handle errors — make your code robust

Quick Check: What is the most important check before copying a file? (Answer: Verify the source file exists)

Try It Yourself

Experiment with copying files in the editor below. Try different copy methods and see the results.

Loading Pyodide... 0%
Python Code Editor
========================================
COPY FILE PRACTICE
========================================

1. CREATING SAMPLE FILE
✅ Created: sample.txt

2. SHUTIL.COPY()
✅ Copied: sample.txt → copy1.txt

3. SHUTIL.COPY2()
✅ Copied: sample.txt → copy2.txt

4. SHUTIL.COPYFILE()
✅ Copied: sample.txt → copy3.txt

5. COPY TO DIRECTORY
✅ Copied: sample.txt → backup/sample_backup.txt

6. VERIFYING COPIES
✅ copy1.txt matches original
✅ copy2.txt matches original
✅ copy3.txt matches original

Copy file practice complete!
🏆

You've Got It!

You now know multiple ways to copy files in Python. You understand the differences between copy(), copy2(), and copyfile(), and how to handle errors professionally.

Quick Quiz

Test what you've learned:

1. Which function copies file content and permissions?
2. Which function preserves file timestamps?
3. Which function copies file content only?
4. What module provides file copying functions?
5. What should you check before copying a file?

Frequently Asked Questions

What is the difference between copy() and copy2()? ▼

copy() copies the file content and permissions. copy2() copies the content, permissions, and also preserves file timestamps (modification and access times). Use copy2() when you need an exact duplicate.

What is the difference between copy() and copyfile()? ▼

copy() copies the content and permissions, and can copy to a directory. copyfile() copies only the content and requires the destination to be a file path, not a directory. copyfile() is faster but less feature-rich.

Can I copy a file to a different directory? ▼

Yes! Use shutil.copy(source, "destination_directory/") to copy to a directory. The file will keep its original name. To change the name, specify the full path: shutil.copy(source, "destination_directory/new_name.txt").

What's a common interview question about file copying? ▼

Common questions include: "How do you copy a file in Python?" "What is the difference between copy(), copy2(), and copyfile()?" and "How would you copy multiple files in a directory?"

How do I copy a large file efficiently? ▼

For large files, use chunk-based copying to avoid memory issues: read the file in chunks (e.g., 1MB at a time) and write each chunk to the destination. The shutil functions already handle this efficiently for you.

What happens if the destination file already exists? ▼

All shutil copy functions will overwrite the destination file if it exists. There's no warning or confirmation. If you need to check before overwriting, use os.path.exists() to check first.

Where to Go From Here

Now that you can copy files, check out these related topics:

Move File

Learn how to move files between directories.

Learn More →

List Files in Directory

Learn how to list and filter files.

Learn More →

Binary Files

Learn how to read and write binary files.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Rename File Next: Move File →