How to copy certain files from one folder to another using Python?


In the vast domain of computer programming, the skill to manage files and directories efficiently is of utmost significance. Python, a versatile and powerful programming language, offers a plethora of tools to manipulate files efficiently. One common task that frequently arises is the need to copy specific files from one folder to another. In this enlightening article, we will take a peek into the process of achieving this using Python. We will explore various techniques, step−by−step, along with a few practical code examples.

Understanding the Task at Hand

Before we embark on the path to copy files, let's take a moment to understand the essence of the task. The objective is to scan a source folder, identify specific files based on certain criteria, and then duplicate those chosen files into a target folder. We can achieve this by leveraging Python's standard library modules, such as os, shutil, and glob.

Copy All Files

Let's start with a basic example where we copy all files from a source folder to a target folder. We will use the os module to iterate through the files in the source folder and the shutil module to perform the actual copying.

Example

In this example, we define a function copy_all_files that takes the paths of the source and target folders as arguments. We use os.listdir() to obtain a list of all files in the source folder and then iterate through them. For each file, we construct its full path using os.path.join(). The os.path.isfile() function checks if the item is a file (not a directory). If it is a file, we use shutil.copy() to copy it to the target folder.

import os
import shutil

def copy_all_files(source_folder, target_folder):
    for filename in os.listdir(source_folder):
        source_file = os.path.join(source_folder, filename)
        if os.path.isfile(source_file):
            shutil.copy(source_file, target_folder)

# Example usage
copy_all_files('source_folder', 'target_folder')

Copy Files with Specific Extensions

Sometimes, we might only want to copy files with certain extensions. For instance, we might want to copy only .txt files or .jpg images. Let's modify our previous example to achieve this:

Example

In this modified version, we added an additional extension parameter to the function. We then check if each file's name ends with the specified extension before copying it to the target folder.

import os
import shutil

def copy_files_with_extension(source_folder, target_folder, extension):
    for filename in os.listdir(source_folder):
        source_file = os.path.join(source_folder, filename)
        if os.path.isfile(source_file) and filename.endswith(extension):
            shutil.copy(source_file, target_folder)

# Example usage
copy_files_with_extension('source_folder', 'target_folder', '.txt')

Copy Files Based on Filename Patterns

What if we want to copy files based on specific patterns in their names? For instance, we may want to copy all files starting with "report_" or ending with "_final." We can achieve this using the glob module in Python:

Example

In this example, we define a function copy_files_with_pattern that takes the source folder, target folder, and the desired pattern as arguments. We use glob.glob() to obtain a list of file paths that match the specified pattern in the source folder.

import shutil
import glob

def copy_files_with_pattern(source_folder, target_folder, pattern):
    for file_path in glob.glob(os.path.join(source_folder, pattern)):
        if os.path.isfile(file_path):
            shutil.copy(file_path, target_folder)

# Example usage
copy_files_with_pattern('source_folder', 'target_folder', 'report_*')

Copy Files Modified within a Date Range

At times, we might need to copy files that were modified within a specific date range. For instance, we may want to copy all files modified in the last 7 days. Let's explore how we can accomplish this:

Example

In this example, we define a function copy_files_within_date_range that takes the source folder, target folder, and the number of days as arguments. We calculate the cutoff time by subtracting the number of days in seconds from the current time using time.time(). We then check if each file's modification time (os.path.getmtime()) is greater than or equal to the cutoff time before copying it to the target folder.

import shutil
import os
import time

def copy_files_within_date_range(source_folder, target_folder, days):
    cutoff_time = time.time() - days * 86400
    for filename in os.listdir(source_folder):
        source_file = os.path.join(source_folder, filename)
        if os.path.isfile(source_file) and os.path.getmtime(source_file) >= cutoff_time:
            shutil.copy(source_file, target_folder)

# Example usage to copy files modified within the last 7 days
copy_files_within_date_range('source_folder', 'target_folder', 7)

Copy Files Based on File Size

Lastly, let's explore how to copy files based on their sizes. We might want to copy all files larger than a certain size or files within a specific size range. Here's how we can implement it:

Example

In this final example, we define a function copy_files_within_size_range that takes the source folder, target folder, minimum size, and maximum size as arguments. We use os.path.getsize() to obtain the size of each file in bytes and then check if the size falls within the specified range before copying the file to the target folder.

import shutil
import os

def copy_files_within_size_range(source_folder, target_folder, min_size, max_size):
    for filename in os.listdir(source_folder):
        source_file = os.path.join(source_folder, filename)
        if os.path.isfile(source_file):
            file_size = os.path.getsize(source_file)
            if min_size <= file_size <= max_size:
                shutil.copy(source_file, target_folder)

# Example usage to copy files between 1 MB and 10 MB
copy_files_within_size_range('source_folder', 'target_folder', 1000000, 10000000)

In this exhaustive article, we explored different approaches to copying specific files from one folder to another using Python. We started with a basic example that copies all files and then progressed to more specialized cases where we copied files based on extensions, filename patterns, modification dates, and file sizes. Python's standard library modules, such as os, shutil, and glob, proved to be powerful tools for achieving these tasks. Armed with this knowledge, you can now confidently manage file−copying operations in your Python projects with ease. So you go ahead, harness the power of Python, and master the art of file manipulation!

Updated on: 11-Sep-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements