以下是一个示例代码,演示如何复制或移动目录中的所有文件,无论文件夹深度或数量。
import os
import shutil
def copy_files(source_dir, destination_dir):
# 遍历源目录中的所有文件和文件夹
for root, dirs, files in os.walk(source_dir):
# 在目标目录中创建相同的目录结构
dest_path = root.replace(source_dir, destination_dir, 1)
if not os.path.exists(dest_path):
os.makedirs(dest_path)
# 复制或移动文件
for file in files:
src_file = os.path.join(root, file)
dest_file = os.path.join(dest_path, file)
shutil.copy2(src_file, dest_file) # 使用shutil.copy2进行复制操作
#shutil.move(src_file, dest_file) # 使用shutil.move进行移动操作
# 示例用法
source_directory = "/path/to/source/directory"
destination_directory = "/path/to/destination/directory"
copy_files(source_directory, destination_directory)
上述代码使用了os.walk
函数来遍历源目录中的所有文件和文件夹。对于每个文件,使用shutil.copy2
函数进行复制操作,也可以使用shutil.move
函数进行移动操作。在目标目录中创建相同的目录结构可以使用os.makedirs
函数。
请确保将source_directory
和destination_directory
替换为实际的源目录和目标目录路径。