Batch Copy Specific Files in Nested Folders Using Python
This article demonstrates how to use Python's shutil and os modules to automatically traverse directories and copy all files containing a given keyword from a folder and its subfolders, saving time compared to manual copying.
Introduction
The author encountered a request to copy specific files (e.g., those containing "需求单") from a folder and all its subfolders, which would be tedious to do manually when dealing with hundreds of directories.
Requirement Clarification
The goal is to automate the process with Python, copying every file whose name includes the target keyword into a designated output folder.
Implementation
The solution iterates through the directory tree using os.walk, checks each filename for the keyword, and copies matching files with shutil.copyfile. The core script is shown below:
import shutil
import os
def copy_file(path):
# (root, dirs, files) represent the current directory, its subdirectories, and files
for root, dirs, files in os.walk(path):
for file in files:
if "需求单" in file:
shutil.copyfile(root + '\\' + file, target_path + '\\' + file)
print(root + '\\' + file + ' 复制成功-> ' + target_path)
for dir_in in dirs:
copy_file(dir_in)
if __name__ == '__main__':
# Folder to search
source_path = r'C:\Users\pdcfi\Desktop\test\需求单'
# Destination folder
target_path = r'C:\Users\pdcfi\Desktop\test\res'
copy_file(source_path)Running this script copies all matching files from the source directory and its subdirectories to the target directory, eliminating the need for manual copying.
Conclusion
The example showcases a practical Python automation case for file handling that can be adapted to various real‑world tasks.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
