递归方法,将某目录下的文件以及该目录的子目录下的文件,复制到指定目录,保持原文件目录
# 将目录的文件复制到指定目录
def copy_demo(src_dir, dst_dir):
"""
复制src_dir目录下的所有内容到dst_dir目录
:param src_dir: 源文件目录
:param dst_dir: 目标目录
:return:
"""
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
if os.path.exists(src_dir):
for file in os.listdir(src_dir):
file_path = os.path.join(src_dir, file)
dst_path = os.path.join(dst_dir, file)
if os.path.isfile(os.path.join(src_dir, file)):
copyfile(file_path, dst_path)
else:
copy_demo(file_path, dst_path)
该博客介绍了一个使用Python的递归方法来复制一个目录及其所有子目录下的文件到指定目标目录的函数。函数首先检查目标目录是否存在,如果不存在则创建,然后遍历源目录,对于每个文件,如果它是文件则直接复制,如果是目录则递归调用自身进行复制,从而保持原文件目录结构。

被折叠的 条评论
为什么被折叠?



