你可以使用Python的shutil模块来复制指定扩展名的文件,并保留文件夹树结构。下面是一个示例代码:
import os
import shutil
def copy_files_with_extension(source_dir, target_dir, extension):
# 检查目标文件夹是否存在,如果不存在则创建
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# 遍历源文件夹及其子文件夹
for root, dirs, files in os.walk(source_dir):
# 在目标文件夹中创建对应的子文件夹
target_subdir = os.path.join(target_dir, os.path.relpath(root, source_dir))
if not os.path.exists(target_subdir):
os.makedirs(target_subdir)
# 复制指定扩展名的文件到目标文件夹中
for file in files:
if file.endswith(extension):
source_file = os.path.join(root, file)
target_file = os.path.join(target_subdir, file)
shutil.copy2(source_file, target_file)
# 示例用法
source_directory = './source'
target_directory = './target'
file_extension = '.txt'
copy_files_with_extension(source_directory, target_directory, file_extension)
在上面的示例代码中,copy_files_with_extension
函数接受三个参数:源文件夹路径,目标文件夹路径以及要复制的文件的扩展名。首先,我们检查目标文件夹是否存在,如果不存在则创建。然后,我们使用os.walk
遍历源文件夹及其子文件夹。对于每个子文件夹,我们在目标文件夹中创建对应的子文件夹。最后,我们使用shutil.copy2
复制指定扩展名的文件到目标文件夹中。
上一篇:保留文件的最新版本
下一篇:保留文件路径的read.csv