How to Efficiently Copy Files Multiple Times Using Python — A Handy Script!

ByteX
2 min read1 day ago

--

Hello everyone!

It’s been a while since I last shared a script, but here’s something super practical that many of you might find useful. Imagine a scenario where you need to copy the same file hundreds, thousands, or even tens of thousands of times — tedious, right? Instead of manually doing this or running repetitive commands, here’s a Python script that can save the day!

The Use Case

This script is perfect for:

  1. Testing Scenarios: Need thousands of identical files to test file processing systems or simulate loads?
  2. Data Duplication: Quickly generate a specific number of identical file copies.
  3. Development Workflows: When working on automation scripts or experiments requiring large datasets of the same structure.

The Script
Here’s the magic:

import os 
import shutil

def copy_file_multiple_times(source_files, destination_folder, num_copies):
# Ensure the destination folder exists, if not, create it
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)

# Iterate through each source file
for source_file in source_files:
# Check if the source file exists
if not os.path.exists(source_file):
print(f"Source file does not exist: {source_file}")
continue

# Get the file name from the source file path
file_name = os.path.basename(source_file)

# Copy the file multiple times
for i in range(1, num_copies + 1):
destination_file = os.path.join(destination_folder, f"{i}_{file_name}")
try:
shutil.copy(source_file, destination_file)
print(f"Copied: {source_file} -> {destination_file}")
except Exception as e:
print(f"Error copying file {source_file} to {destination_file}: {e}")

# Example Usage
source_files = [
r'C:\path\to\your\file1.txt',
r'C:\path\to\your\file2.txt'
] # List of source files to copy

destination_folder = r'C:\path\to\destination\folder' # Ensure paths are correct
num_copies = 2500 # Number of copies you want to make for each file

copy_file_multiple_times(source_files, destination_folder, num_copies)

Tips: Use raw strings (r”path”) or forward slashes (/) for clean, cross-platform paths for windows environment like [path = “D:\\Project\\Projects\\vulnerable-node-master\\bin”] or [path = r”D:\Project\Projects\vulnerable-node-master\bin”]

Why This Script?

  • Simplicity: Minimal code with robust error handling.
  • Customizable: Modify the num_copies or file paths as per your requirements.
  • Scalability: Handles thousands of file copies without breaking a sweat.

Let’s Discuss!

I’d love to hear how you might use this script! Whether for testing or creative automation tasks, drop your thoughts and feedback in the comments below. 👇

If you have any ideas for improving this or other scripts, feel free to share! Until next time, happy coding! 🎉

Here’s the magic:

--

--

No responses yet