下面是一个示例脚本,用于将每个目录中的两个文件复制到相应的目录中:
import os
import shutil
# 获取当前目录下的所有子目录
directories = [d for d in os.listdir('.') if os.path.isdir(os.path.join('.', d))]
# 遍历每个子目录
for directory in directories:
# 在每个子目录中获取前两个文件
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
files_to_copy = files[:2] # 只复制前两个文件
# 在当前目录下创建目标目录
target_directory = os.path.join('目标目录', directory)
os.makedirs(target_directory, exist_ok=True)
# 将文件复制到目标目录
for file in files_to_copy:
source_path = os.path.join(directory, file)
target_path = os.path.join(target_directory, file)
shutil.copy2(source_path, target_path)
上述代码假设脚本文件位于需要操作的目录下,并将复制后的文件放在名为“目标目录”的目录中。你需要根据实际情况修改脚本中的“目标目录”为你想要的目标目录名称。
请注意,上面的示例代码使用了Python的os和shutil模块来进行文件和目录操作。os模块用于与操作系统交互,shutil模块用于高级文件操作。在使用脚本之前,请确保你已经安装了Python,并且具备基本的Python编程知识。