Automate Selective Folder Copying in Python: Two‑Step Script Guide
This tutorial explains how to automate selective folder copying in Python using os.walk and shutil, presenting a two‑step approach that first extracts directories starting with “数据” and then those containing “DD”, complete with full code examples and execution tips.
Introduction
In a Python community a user asked how to automate file copying for large data folders. This article shares a complete solution.
Implementation Process
The original script attempted to copy files but did not meet expectations. The improved approach splits the task into two passes: first copy all directories whose name starts with “数据”, then copy those containing “DD”.
import shutil
import os
def copy_file(path):
for root, dirs, files in os.walk(path):
for dir in dirs:
if "数据" in dir:
shutil.copytree(root + '\\' + dir, target_path + '\\' + dir)
print(root + '\\' + dir + ' copied -> ' + target_path)
for dir in dirs:
if "DD" in dir:
shutil.copytree(root + '\\' + dir, target_path + '\\' + dir)
print(root + '\\' + dir + ' copied -> ' + target_path)
if __name__ == '__main__':
source_path = r'D:\SupplyChain\Orders'
target_path = r'C:\Users\Desktop\res'
copy_file(source_path)Two separate code snippets illustrate the first‑pass extraction (filtering “数据”) and the second‑pass extraction (filtering “DD”).
Summary
The provided Python script demonstrates how to automate office tasks such as selective folder copying, offering a clear, reproducible solution for the community.
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.
