如何在Python中实现Windows系统下文件夹内容全量复制?
Windows下用Python实现文件夹完整复制的解决方案
要实现Windows系统上复制文件夹全部内容(含子文件和子文件夹)的功能,直接使用Python标准库即可,无需额外安装依赖,以下是可行的解决方案:
方案代码
import os import shutil def copy_folder_contents(source_dir, target_dir): # 确保目标目录存在,不存在则创建 if not os.path.exists(target_dir): os.makedirs(target_dir) # 遍历源目录中的每一项 for item_name in os.listdir(source_dir): source_path = os.path.join(source_dir, item_name) target_path = os.path.join(target_dir, item_name) if os.path.isdir(source_path): # 递归处理子文件夹 copy_folder_contents(source_path, target_path) else: # 复制文件,保留元数据(修改时间等),已存在则覆盖 shutil.copy2(source_path, target_path) # 示例调用(替换为实际路径) if __name__ == "__main__": # Windows路径建议用原始字符串,避免转义字符问题 source_folder = r"C:\Your\Source\Folder" target_folder = r"C:\Your\Target\Folder" copy_folder_contents(source_folder, target_folder) print("文件夹内容复制完成")
关键说明
- 兼容性:仅依赖Python标准库
os和shutil,所有安装了Python的Windows系统都能运行 - 完整复制:递归处理所有子文件夹,
shutil.copy2()会保留文件的元数据(如修改时间、权限等),比基础的shutil.copy()更完整 - 路径处理:使用
os.path.join()拼接路径,适配Windows的路径格式;原始字符串r""避免反斜杠转义问题
可选优化
如果需要避免覆盖已有文件,可以在复制文件前增加判断:
if not os.path.exists(target_path): shutil.copy2(source_path, target_path) else: print(f"文件 {target_path} 已存在,跳过复制")
内容的提问来源于stack exchange,提问作者sukanto Kundu
相关产品推荐
相关产品推荐

