在 Python 中复制文件夹有两种方法:使用 shutil.copytree() 函数递归复制文件夹和内容。使用 os 模块创建目标文件夹,遍历源文件夹并复制文件。

如何使用 Python 复制文件夹
在 Python 中复制文件夹非常简单,可以通过以下方法实现:
1. 使用 shutil 模块
shutil 模块提供了一个 copytree() 函数,它可以递归地复制整个文件夹及其所有内容。
立即学习“Python免费学习笔记(深入)”;
<code class="python">import shutil # 源文件夹路径 source_dir = "源文件夹路径" # 目标文件夹路径 target_dir = "目标文件夹路径" # 复制文件夹 shutil.copytree(source_dir, target_dir)</code>
2. 使用 os 模块
os 模块提供了一些低级函数,可以通过以下步骤手动复制文件夹:
创建目标文件夹
<code class="python">import os # 目标文件夹路径 target_dir = "目标文件夹路径" # 创建目标文件夹 os.makedirs(target_dir, exist_ok=True)</code>
遍历源文件夹并复制文件
<code class="python"># 源文件夹路径
source_dir = "源文件夹路径"
# 遍历源文件夹下的所有文件和文件夹
for item in os.listdir(source_dir):
# 获取文件或文件夹的绝对路径
source_path = os.path.join(source_dir, item)
# 检查是否为文件
if os.path.isfile(source_path):
# 复制文件
target_path = os.path.join(target_dir, item)
with open(source_path, "rb") as source_file, open(target_path, "wb") as target_file:
shutil.copyfileobj(source_file, target_file)</code>以上就是python怎么复制文件夹的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号