可以通过以下步骤完成:
os
模块来操作文件和目录。import os
source_dir = '源目录路径'
target_dir = '目标目录路径'
os.walk()
函数遍历源目录中的所有子目录。for root, dirs, files in os.walk(source_dir):
# 在这里编写复制代码
for root, dirs, files in os.walk(source_dir):
for dir_name in dirs:
if '特定名称' in dir_name:
source_path = os.path.join(root, dir_name)
target_path = os.path.join(target_dir, dir_name)
os.makedirs(target_path, exist_ok=True) # 创建目标子目录
for file in os.listdir(source_path):
file_path = os.path.join(source_path, file)
if os.path.isfile(file_path):
shutil.copy(file_path, target_path) # 复制文件
以上代码将会遍历源目录中的所有子目录,检查子目录的名称是否包含特定名称,如果是,则创建相应的目标子目录并将该子目录下的文件复制到目标目录中。
请注意,以上代码中使用了shutil.copy()
函数来复制文件,因此需要导入shutil
模块。
import shutil
最后,将以上代码整合到一个Python脚本中,运行该脚本即可实现按名称复制特定子目录。
领取专属 10元无门槛券
手把手带您无忧上云