这段代码主要是为了保留原格式的情况下批量去复制文件夹里特定的文件,主要运用场景为:如你有一个文件包,里面有许多不同的子文件夹,但是许多不同的子文件下又有许多相同的子文件,就可以通过此代码去得到想要的效果。
import os
import shutil
def copy_folders(source_dir, destination_dir, folders_to_copy):
if not os.path.exists(destination_dir):
os.makedirs(destination_dir)
for root, dirs, files in os.walk(source_dir):
for dir_name in dirs[:]: # 遍历当前目录下的所有子文件夹
if dir_name in folders_to_copy: # 如果子文件夹名在指定的复制列表中
source_subdir = os.path.join(root, dir_name)
destination_subdir = os.path.join(destination_dir, os.path.relpath(source_subdir, source_dir))
# 创建目标子文件夹(如果不存在)
if not os.path.exists(destination_subdir):
os.makedirs(destination_subdir)
# 复制子文件夹及其内容到目标位置
for file in os.listdir(source_subdir):
source_file = os.path.join(source_subdir, file)
destination_file = os.path.join(destination_subdir, file)
shutil.copy2(source_file, destination_file)
print(f'Copied {file} to {destination_subdir}')
# 需要读取的文件位置
source_directory = 'F:\\读取路径'
destination_directory = 'F:\\接收路径' # 读取后存放的位置
folders_to_copy = ['名字一', '名字二'] # 需要读取的文件名
copy_folders(source_directory, destination_directory, folders_to_copy)
最后希望对大家有帮助!