在Python中,你可以使用`shutil`模块来拷贝文件夹及其内容。以下是两种常见的拷贝方式:
1. 拷贝整个文件夹(包括子目录和文件):
```python
import os
import shutil
source_path = os.path.abspath('E:\\Projects\\source_dir')
target_path = os.path.abspath('E:\\Projects\\new_folder\\target_dir')
如果目标路径不存在,则创建
if not os.path.exists(target_path):
os.makedirs(target_path)
使用shutil.copytree()函数拷贝整个目录
shutil.copytree(source_path, target_path)
print('copy dir finished!')
2. 遍历源文件夹,拷贝所有文件到目标文件夹:
```python
import os
import shutil
source_path = os.path.abspath('E:\\Projects\\source_dir')
target_path = os.path.abspath('E:\\Projects\\new_folder\\target_dir')
如果目标路径不存在,则创建
if not os.path.exists(target_path):
os.makedirs(target_path)
遍历源文件夹
for item in os.listdir(source_path):
src_item = os.path.join(source_path, item)
dst_item = os.path.join(target_path, item)
如果是文件,则直接复制
if os.path.isfile(src_item):
shutil.copy2(src_item, dst_item)
如果是文件夹,则递归调用copy_dir函数
elif os.path.isdir(src_item):
copy_dir(src_item, dst_item)
def copy_dir(src, dst):
if not os.path.exists(src):
return
if not os.path.exists(dst):
os.mkdir(dst)
pathes = os.listdir(src)
for p in pathes:
f_path = os.path.join(src, p)
dst_path = f_path.replace(src, dst)
if os.path.isfile(f_path):
shutil.copy2(f_path, dst_path)
elif os.path.isdir(f_path):
copy_dir(f_path, dst_path)
以上代码示例展示了如何使用`shutil.copytree()`函数来拷贝整个文件夹,以及如何遍历文件夹并递归地拷贝所有文件和子文件夹。使用`shutil.copy2()`函数可以在拷贝文件的同时保留文件的元数据(如时间戳)。
请根据你的具体需求选择合适的拷贝方法