python import os import shutil def find_and_copy_or_delete(source_dir, target_name, operation): for root, dirs, files in os.walk(source_dir): for name in dirs + files: if name == target_name: file_path = os.path.join(root, name) if operation == 'copy': # 复制文件或目录 shutil.copy(file_path, '/path/to/destination') print(f'Copied {file_path} to destination') elif operation == 'delete': # 删除文件或目录 if os.path.isfile(file_path): os.remove(file_path) print(f'Deleted file: {file_path}') else: shutil.rmtree(file_path) print(f'Deleted directory: {file_path}') # 用法示例 # 在指定目录下查找名为 "target_directory" 的目录,并复制到目标目录 source_directory = '/path/to/source_directory' target_directory_name = 'target_directory' find_and_copy_or_delete(source_directory, target_directory_name, 'copy') # 在指定目录下查找名为 "target_file.txt" 的文件,并删除 source_directory = '/path/to/source_directory' target_file_name = 'target_file.txt' find_and_copy_or_delete(source_directory, target_file_name, 'delete') 在这个示例中,find_and_copy_or_delete 函数接受三个参数:源目录路径、目标名称和操作类型(复制或删除)。它使用 os.walk 遍历源目录及其子目录,并对每个文件或目录进行匹配和操作。
python递归查询目录下所有文件以及文件夹并进行复制或删除操作
最新推荐文章于 2024-08-10 04:00:51 发布