温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python如何复制文件夹

发布时间:2022-05-09 16:18:55 来源:亿速云 阅读:5122 作者:iii 栏目:大数据

这篇文章主要介绍了python如何复制文件夹的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇python如何复制文件夹文章都会有所收获,下面我们一起来看看吧。

具体操作方法:

1、首先需要在python脚本中导入os, shutil模块进行文件操作。

import os, shutil


2、再使用copy函数进行文件夹复制操作即可。

shutil.copy(source_file,target_ir) #source_file指源路径, target_ir指目标路径


实例代码:

1、文件夹整体拷贝。

import os

import shutil


source_path = os.path.abspath(r'E:\Projects\source_dir')

target_path = os.path.abspath(r'E:\Projects\new folder\target_dir')


if not os.path.exists(target_path):

# 如果目标路径不存在原文件夹的话就创建

os.makedirs(target_path)


if os.path.exists(source_path):

# 如果目标路径存在原文件夹的话就先删除

shutil.rmtree(target_path)


shutil.copytree(source_path, target_path)

print('copy dir finished!')


2、文件夹下的所有文件拷贝到目标文件夹下。

import os

import shutil


source_path = os.path.abspath(r'E:\Projects\source_dir')

target_path = os.path.abspath(r'E:\Projects\target_dir')


if not os.path.exists(target_path):

os.makedirs(target_path)


if os.path.exists(source_path):

# root 所指的是当前正在遍历的这个文件夹的本身的地址

# dirs 是一个 list,内容是该文件夹中所有的目录的名字(不包括子目录)

# files 同样是 list, 内容是该文件夹中所有的文件(不包括子目录)

for root, dirs, files in os.walk(source_path):

for file in files:

src_file = os.path.join(root, file)

shutil.copy(src_file, target_path)

print(src_file)


print('copy files finished!')


相关函数:

os.remove #删除文件

os.rmdir #删除文件夹

shutil.rmtree #删除目录及其所有内容


关于“python如何复制文件夹”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“python如何复制文件夹”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI